Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
fix(runtime): check exact approved game build readiness
domsvobodaa29420478485
diff --git a/src/main/game-runtime-readiness.ts b/src/main/game-runtime-readiness.tsnew file mode 100644index 0000000..dc6c2e2--- /dev/null+++ b/src/main/game-runtime-readiness.ts@@ -0,0 +1,20 @@+import type {Game} from '../shared/types.js';+import {resolveGameRuntime} from './runtime-prefix-binding.js';+export interface RuntimeReadinessState {+ game?:Pick<Game,'id'|'runtime'|'runtimeSeparatePrefix'|'runtimeBuild'>;+ runtimeRoot:string;dataRoot:string;defaultWine:string|undefined;arch?:string;+}+function identity(state:RuntimeReadinessState):string {+ const game=state.game;+ return JSON.stringify([game?.id,game?.runtime,game?.runtimeSeparatePrefix,game?.runtimeBuild?.buildId,game?.runtimeBuild?.manifestSha256,game?.runtimeBuild?.sourceCommit,state.runtimeRoot,state.dataRoot,state.defaultWine,state.arch]);+}+/** Read-only readiness hint. No prefix binding, runtime execution or account+ * queries. Actual launch independently resolves and verifies its captured build. */+export async function gameRuntimeReadiness(read:()=>RuntimeReadinessState,resolve=resolveGameRuntime):Promise<boolean> {+ try {+ const state=structuredClone(read()),before=identity(state);+ if(!state.game)return false;+ await resolve({runtimeRoot:state.runtimeRoot,dataRoot:state.dataRoot,gameId:state.game.id,selection:state.game.runtime,separatePrefix:state.game.runtimeSeparatePrefix,approvedBuild:state.game.runtimeBuild,defaultWine:state.defaultWine,arch:state.arch});+ return before===identity(read());+ }catch{return false;}+}diff --git a/src/main/index.ts b/src/main/index.tsindex 04615f0..0fa1ff2 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1,3 +1,4 @@+import {gameRuntimeReadiness} from './game-runtime-readiness.js';import {approvedRuntimeSettings,type RuntimeSettingsRequest} from './runtime-settings.js';import {gameRuntimeSelection} from '../shared/runtime-selection.js';import {resolveGameRuntime,bindRuntimePrefix} from './runtime-prefix-binding.js';@@ -1708,6 +1709,7 @@ function registerDemoIpc(catalogMarket: () => string): void {return { ...game, ...patch };});ipcMain.handle('remove-game', () => {});+ ipcMain.handle('game-runtime-readiness', () => false); // Synthetic demo never validates managed payloads.ipcMain.handle('game-launch-options', () => demoLaunchOptions);ipcMain.handle('game-details', async (_event, id: unknown) => {const game = demoGames.find(game => game.id === id);@@ -2076,6 +2078,7 @@ function registerIpc(): void {gameRemovalInProgress = false;}});+ ipcMain.handle('game-runtime-readiness', (_event, id: string) => gameRuntimeReadiness(()=>({game:store.games.find(game=>game.id===id),runtimeRoot:store.settings.runtimeRoot,dataRoot:path.dirname(store.settings.runtimeRoot),defaultWine:selectedWinePath(store.settings.winePath,store.settings.runtimeRoot,runtime.current.winePath)})));ipcMain.handle('game-launch-options', (_event, id: string) => gameLaunchOptions(id));ipcMain.handle('game-details', async (_event, id: unknown) => {const target=gameDetailsTarget(id,store.games);diff --git a/src/main/runtime-families.test.ts b/src/main/runtime-families.test.tsindex cfa9c10..845506b 100644--- a/src/main/runtime-families.test.ts+++ b/src/main/runtime-families.test.ts@@ -1,3 +1,4 @@+import {gameRuntimeReadiness,type RuntimeReadinessState} from './game-runtime-readiness';import {afterEach,beforeEach,describe,expect,it,vi} from 'vitest';import {promises as fs} from 'node:fs';import path from 'node:path';@@ -356,3 +357,20 @@ it('fails closed when retained A payload disappears while current B remains valiawait expect(resolveRuntimeFamilyBuild(root,family,a,'x64')).rejects.toThrow('default was not used');expect((await resolveRuntimeFamily(root,family,'x64')).buildId).not.toBe(buildId);});++it('reports retained A ready with missing or corrupt current B, but never missing or corrupt A',async()=>{+ await fixture();const a=await approval();await retainRuntimeFamilyBuild(root,family,'x64');const previous=await installNextFixture();+ const state:RuntimeReadinessState={game:{id:'readiness',runtime:family,runtimeSeparatePrefix:true,runtimeBuild:a},runtimeRoot:root,dataRoot:root,defaultWine:undefined,arch:'x64'};+ const current=path.join(root,'variants',family,'current.json');await fs.writeFile(current,'{corrupt B');+ expect(await gameRuntimeReadiness(()=>state)).toBe(true);await fs.unlink(current);expect(await gameRuntimeReadiness(()=>state)).toBe(true);+ await fs.appendFile(path.join(previous,'files/bin/wine'),'corrupt A');expect(await gameRuntimeReadiness(()=>state)).toBe(false);+ await fs.rm(previous,{recursive:true});expect(await gameRuntimeReadiness(()=>state)).toBe(false);+ await expect(fs.access(path.join(root,'runtime-prefixes'))).rejects.toThrow();+});+it.each(['approval','runtimeRoot'])('rejects readiness if %s changes during verification',async changed=>{+ await fixture();const state:RuntimeReadinessState={game:{id:'readiness',runtime:family,runtimeSeparatePrefix:true,runtimeBuild:await approval()},runtimeRoot:root,dataRoot:root,defaultWine:undefined,arch:'x64'};+ let resume!:()=>void;const held=new Promise<void>(resolve=>resume=resolve);+ const result=gameRuntimeReadiness(()=>state,async options=>{await held;return resolveGameRuntime(options);});+ if(changed==='approval')state.game={...state.game!,runtimeBuild:{...state.game!.runtimeBuild!,buildId:'d'.repeat(64)}};else state.runtimeRoot+='-changed';+ resume();expect(await result).toBe(false);+});diff --git a/src/preload/index.cts b/src/preload/index.ctsindex 74d8825..a54286b 100644--- a/src/preload/index.cts+++ b/src/preload/index.cts@@ -135,6 +135,7 @@ const api: LauncherApi = {updateGame: (id: string, patch: Partial<Pick<Game, 'title' | 'executable' | 'launchArgs' | 'locale' | 'launchTools'>>) => ipcRenderer.invoke('update-game', id, patch),getGameLocales: (id: string) => ipcRenderer.invoke('game-locales', id),removeGame: (id: string, mode: 'library' | 'delete-files') => ipcRenderer.invoke('remove-game', id, mode),+ getGameRuntimeReadiness: (id: string) => ipcRenderer.invoke('game-runtime-readiness', id),getGameLaunchOptions: (id: string) => ipcRenderer.invoke('game-launch-options', id),getGameDetails: (id: import('../shared/types').GameDetailsTarget) => ipcRenderer.invoke('game-details', id),getGameActivity: (id: import('../shared/types').GameDetailsTarget, refresh?: boolean) => ipcRenderer.invoke('game-activity', id, refresh),diff --git a/src/renderer/App.tsx b/src/renderer/App.tsxindex 6052a91..10d257a 100644--- a/src/renderer/App.tsx+++ b/src/renderer/App.tsx@@ -1,6 +1,7 @@+import {useGameRuntimeReady} from './useGameRuntimeReady';import {useStoreAccess} from './store-access';import {GameRuntimeFields} from './GameRuntimeFields';-import {gameRuntimeAvailable,sameRuntimeBuild,runtimeBuildApproval,type InstalledRuntimeFamily,type RuntimeBuildApproval,type GameRuntimeSelection} from '../shared/runtime-selection';+import {sameRuntimeBuild,runtimeBuildApproval,type InstalledRuntimeFamily,type RuntimeBuildApproval,type GameRuntimeSelection} from '../shared/runtime-selection';import { CloudSaveWarning } from './CloudSaveWarning';import { CheckField } from './CheckField';import { useDialogFocus } from './use-dialog-focus';@@ -221,7 +222,8 @@ export function HomePage({ data, go, action, openGame, returnFocusKey }: {data: AppSnapshot; go: (page: Page) => void; action: (fn: () => Promise<unknown>, success?: string) => void; openGame?: (id: string, returnKey: string) => void; returnFocusKey?: string;}) {const featured = data.games[0];- const canPlay = Boolean(featured?.installState === 'ready' && data.backend.capabilities.run && gameRuntimeAvailable(featured?.runtime,featured?.runtimeSeparatePrefix,Boolean(data.settings.winePath||data.runtime.winePath),data.runtime.variants??[]));+ const featuredRuntimeReady=useGameRuntimeReady(featured,data);+ const canPlay = Boolean(featured?.installState === 'ready' && data.backend.capabilities.run && featuredRuntimeReady);const launchOptions = useGameLaunchOptions(featured, data);const spotlightArt = featured?.heroUrl ?? featured?.coverUrl;const home = useRef<HTMLElement>(null);@@ -812,6 +814,7 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,const selectedOperation = selected && data.gameOperation?.gameId === selected.id ? data.gameOperation : undefined;const gameBusy = Boolean(selectedOperation && ['preparing', 'running', 'stopping'].includes(selectedOperation.status));+ const selectedRuntimeReady=useGameRuntimeReady(selected,data);const launchOptions = useGameLaunchOptions(selected, data);const menuGame = data.games.find((game) => game.id === menu?.id);const modalGame = data.games.find((game) => game.id === dialogGame?.id);@@ -836,7 +839,7 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,contentDisabled: !game.storeId || data.auth.stored !== true || !data.backend.capabilities.library,});const selectedPanel = catalogProduct&&detailVisible?<CatalogGameDetails key={catalogProduct.productId+catalogScope} product={catalogProduct} data={data} back={closeDetails} toast={toast}/>:!catalogSelection&&selected&&detailVisible ? <GameDetails key={`${selected.id}:${data.auth.username}:${data.auth.player}:${data.auth.stored}:${data.auth.running}:${data.backend.binaryPath}:${data.settings.market}`} game={selected} data={data} back={closeDetails} backLabel={returnHomeKey.current ? ui('game.back_to_home') : undefined} play={<>- <button className="primary" data-gamepad-play disabled={gameBusy || selected.installState !== 'ready' || !data.backend.capabilities.run || !gameRuntimeAvailable(selected.runtime,selected.runtimeSeparatePrefix,Boolean(data.settings.winePath||data.runtime.winePath),data.runtime.variants??[])} onClick={() => play()}>{gameBusy ? <LoaderCircle className="spin" /> : <Play fill="currentColor" />}{gameBusy ? ui("ui.working_5474eef") : ui("ui.play_436e610")}</button>+ <button className="primary" data-gamepad-play disabled={gameBusy || selected.installState !== 'ready' || !data.backend.capabilities.run || !selectedRuntimeReady} onClick={() => play()}>{gameBusy ? <LoaderCircle className="spin" /> : <Play fill="currentColor" />}{gameBusy ? ui("ui.working_5474eef") : ui("ui.play_436e610")}</button>{gameBusy && !(selectedOperation?.kind === 'prerequisite' && selectedOperation.status === 'running') ? <button className="secondary danger" onClick={stopGame}><X />{ui("ui.stop_cae7d57")}</button> : null}</>} manage={<GameMenuActions {...managementProps(selected)} />} technical={<dl><div><dt>{ui("ui.store_id_4a3eac6")}</dt><dd>{selected.storeId ?? ui("ui.not_found_e3ebaa1")}</dd></div><div><dt>{ui("ui.executable_72cd8a6")}</dt><dd>{selected.executable ?? ui("ui.not_found_e3ebaa1")}</dd></div><div><dt>{ui("ui.location_15b6197")}</dt><dd>{selected.path}</dd></div></dl>} notices={<>{selected.installMessage ? <div className="alert amber"><CircleAlert /><span>{uiText(selected.installMessage)}</span></div> : null}diff --git a/src/renderer/CatalogGameDetails.tsx b/src/renderer/CatalogGameDetails.tsxindex e75bdff..5ba8468 100644--- a/src/renderer/CatalogGameDetails.tsx+++ b/src/renderer/CatalogGameDetails.tsx@@ -4,7 +4,7 @@ import type {AppSnapshot,CatalogProduct} from '../shared/types';import {GameDetails} from './GameDetails';import {catalogInstallRequest,usePackageInstall} from './PackageInstall';import {useStoreAccess} from './store-access';-import {gameRuntimeAvailable} from '../shared/runtime-selection';+import {useGameRuntimeReady} from './useGameRuntimeReady';import {ui,uiText} from './i18n';export function catalogGameInstalled(product:CatalogProduct,data:AppSnapshot){@@ -36,7 +36,8 @@ export function CatalogGameDetails({product,data,back,backLabel,toast,storeAcces}catch(error){if(identity.current===scope)toast({kind:'error',message:error instanceof Error?error.message:String(error)});}finally{pending.current=false;setBusy(false);}}- const playDisabled=busy||installed?.installState!=='ready'||!data.backend.capabilities.run||!gameRuntimeAvailable(installed?.runtime,installed?.runtimeSeparatePrefix,Boolean(data.settings.winePath||data.runtime.winePath),data.runtime.variants??[]);+ const runtimeReady=useGameRuntimeReady(installed,data);+ const playDisabled=busy||installed?.installState!=='ready'||!data.backend.capabilities.run||!runtimeReady;async function play(){if(!installed||playDisabled)return;setBusy(true);try{await window.launcher.launchGame(installed.id);}diff --git a/src/renderer/game-runtime-readiness.test.tsx b/src/renderer/game-runtime-readiness.test.tsxnew file mode 100644index 0000000..ccd63b0--- /dev/null+++ b/src/renderer/game-runtime-readiness.test.tsx@@ -0,0 +1,61 @@+// @vitest-environment jsdom+import {act} from 'react';+import {createRoot,type Root} from 'react-dom/client';+import {afterEach,beforeEach,expect,it,vi} from 'vitest';+import {useGameRuntimeReady} from './useGameRuntimeReady';+import {HomePage} from './App';+import {demoSnapshot} from '../shared/demo-data';+let root:Root,data:ReturnType<typeof demoSnapshot>;+const approval={buildId:'a'.repeat(64),manifestSha256:'b'.repeat(64),sourceCommit:'c'.repeat(40)};+const pending=()=>{let resolve!:(ready:boolean)=>void;const promise=new Promise<boolean>(r=>resolve=r);return {promise,resolve};};+function Fixture(){const ready=useGameRuntimeReady(data.games[0],data);return <button disabled={!ready}>Play</button>;}+const render=()=>act(async()=>root.render(<Fixture/>));+const enabled=()=>!(document.querySelector('button') as HTMLButtonElement).disabled;+beforeEach(()=>{+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);data=demoSnapshot();data.games=[{...data.games[0],runtime:'nexus-cachyos',runtimeSeparatePrefix:true,runtimeBuild:approval}];data.runtime.variants=[];+ window.launcher={getGameRuntimeReadiness:vi.fn(async()=>true)} as unknown as Window['launcher'];+ document.body.innerHTML='<div id="root"></div>';root=createRoot(document.getElementById('root')!);+});+afterEach(async()=>{await act(async()=>root.unmount());vi.restoreAllMocks();vi.unstubAllGlobals();});+it('uses exact approved readiness even with no current family, and avoids rerender request loops',async()=>{+ const request=pending();vi.mocked(window.launcher.getGameRuntimeReadiness).mockReturnValue(request.promise);+ await render();expect(enabled()).toBe(false);await act(async()=>request.resolve(true));expect(enabled()).toBe(true);+ await render();await render();expect(window.launcher.getGameRuntimeReadiness).toHaveBeenCalledTimes(1);+});+it('never borrows current B availability when approved A is missing or verification fails',async()=>{+ data.runtime.variants=[{id:'nexus-cachyos',label:'B',buildId:'d'.repeat(64),manifestSha256:'e'.repeat(64),sourceCommit:'f'.repeat(40)}];+ vi.mocked(window.launcher.getGameRuntimeReadiness).mockResolvedValue(false);await render();expect(enabled()).toBe(false);+ vi.mocked(window.launcher.getGameRuntimeReadiness).mockRejectedValue(Error('verification failed'));data.settings.runtimeRoot+='-changed';await render();expect(enabled()).toBe(false);+});+it('rejects stale A-to-B responses and old A results after an A-to-B-to-A switch',async()=>{+ const a=pending(),b=pending(),again=pending();vi.mocked(window.launcher.getGameRuntimeReadiness).mockReturnValueOnce(a.promise).mockReturnValueOnce(b.promise).mockReturnValueOnce(again.promise);+ await render();await act(async()=>a.resolve(true));expect(enabled()).toBe(true);+ data.games=[{...data.games[0],runtimeBuild:{...approval,buildId:'d'.repeat(64)}}];await render();expect(enabled()).toBe(false);+ data.games=[{...data.games[0],runtimeBuild:approval}];await render();expect(enabled()).toBe(false);+ await act(async()=>b.resolve(true));expect(enabled()).toBe(false);+ await act(async()=>again.resolve(true));expect(enabled()).toBe(true);+});+it('ignores a held response after unmount and starts pending on remount',async()=>{+ const old=pending(),fresh=pending();vi.mocked(window.launcher.getGameRuntimeReadiness).mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise);+ await render();await act(async()=>root.render(null));await act(async()=>old.resolve(true));await render();expect(enabled()).toBe(false);+ await act(async()=>fresh.resolve(false));expect(enabled()).toBe(false);+});+it('preserves default/custom Wine readiness without managed verification calls',async()=>{+ data.games=[{...data.games[0],runtime:'default'}];data.settings.winePath='/custom/wine';await render();expect(enabled()).toBe(true);expect(window.launcher.getGameRuntimeReadiness).not.toHaveBeenCalled();+ data.settings.winePath='';data.runtime.winePath=undefined;await render();expect(enabled()).toBe(false);+});++it('ignores held A readiness after switching to B',async()=>{+ const a=pending(),b=pending();vi.mocked(window.launcher.getGameRuntimeReadiness).mockReturnValueOnce(a.promise).mockReturnValueOnce(b.promise);+ await render();data.games=[{...data.games[0],runtimeBuild:{...approval,buildId:'d'.repeat(64)}}];await render();+ await act(async()=>a.resolve(true));expect(enabled()).toBe(false);await act(async()=>b.resolve(true));expect(enabled()).toBe(true);+});++it('enables the actual Home Play action for verified retained A with no current descriptor',async()=>{+ const request=pending();vi.mocked(window.launcher.getGameRuntimeReadiness).mockReturnValue(request.promise);+ window.launcher.getGameLaunchOptions=vi.fn(async()=>({cloudSaves:false,vcInstall:false}));+ data.games[0].installState='ready';data.backend.capabilities.run=true;+ await act(async()=>root.render(<HomePage data={data} go={()=>{}} action={()=>{}}/>));+ const play=()=>document.querySelector<HTMLButtonElement>('[data-gamepad-key="home-play"]');+ expect(play()).toBeNull();await act(async()=>request.resolve(true));expect(play()?.disabled).toBe(false);+});diff --git a/src/renderer/useGameRuntimeReady.ts b/src/renderer/useGameRuntimeReady.tsnew file mode 100644index 0000000..fe65e44--- /dev/null+++ b/src/renderer/useGameRuntimeReady.ts@@ -0,0 +1,25 @@+import {useEffect,useRef,useState} from 'react';+import type {AppSnapshot,Game} from '../shared/types';+/** Exact visible-game readiness, separate from current-build discovery. Pending+ * and errors never borrow another build's availability. */+export function useGameRuntimeReady(game:Game|undefined,data:AppSnapshot):boolean {+ const managed=Boolean(game?.runtime&&game.runtime!=='default');+ const scope=JSON.stringify([game?.id,game?.runtime,game?.runtimeSeparatePrefix,game?.runtimeBuild?.buildId,game?.runtimeBuild?.manifestSha256,game?.runtimeBuild?.sourceCommit,data.settings.runtimeRoot,data.settings.winePath,data.runtime.winePath,(data.runtime.variants??[]).map(item=>[item.id,item.buildId,item.manifestSha256,item.sourceCommit])]);+ const current=useRef({scope,version:0});+ if(current.current.scope!==scope)current.current={scope,version:current.current.version+1};+ const version=current.current.version;+ const epoch=useRef(0);+ const [result,setResult]=useState<{scope:string;version:number;ready:boolean}>();+ useEffect(()=>{+ const generation=++epoch.current;+ if(!game||!managed)return;+ let active=true;+ void Promise.resolve().then(()=>window.launcher.getGameRuntimeReadiness(game.id)).then(ready=>{+ if(active&¤t.current.scope===scope&¤t.current.version===version&&epoch.current===generation)setResult({scope,version,ready:ready===true});+ }).catch(()=>{if(active&¤t.current.scope===scope&¤t.current.version===version&&epoch.current===generation)setResult({scope,version,ready:false});});+ return()=>{active=false;epoch.current++;};+ },[scope,version,managed]);+ if(!game)return false;+ if(!managed)return Boolean(data.settings.winePath||data.runtime.winePath);+ return result?.scope===scope&&result.version===version&&result.ready===true;+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex bd0d53c..ef7140d 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -633,6 +633,7 @@ export interface LauncherApi {updateGame(id: string, patch: Partial<Pick<Game, 'title' | 'executable' | 'launchArgs' | 'locale' | 'launchTools' | 'runtime' | 'runtimeSeparatePrefix'>> & {runtimeApproveBuild?:boolean;runtimeExpectedBuild?:RuntimeBuildApproval}): Promise<Game>;getGameLocales(id: string): Promise<string[]>;removeGame(id: string, mode: 'library' | 'delete-files'): Promise<void>;+ getGameRuntimeReadiness(id: string): Promise<boolean>;getGameLaunchOptions(id: string): Promise<GameLaunchOptions>;getGameDetails(id: GameDetailsTarget): Promise<GameStoreDetails | undefined>;getGameActivity(id: GameDetailsTarget, refresh?: boolean): Promise<GameActivity>;