Skip to content

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

TypeScript

fix(runtime): preserve game prefixes across family changes

Nexus Maintainer94b94905b0a8
diff --git a/assets/locales/de.json b/assets/locales/de.json
index 3e4bded..e9dbe06 100644
--- a/assets/locales/de.json
+++ b/assets/locales/de.json
@@ -2,8 +2,6 @@
"runtime.game_runtime": "Spiel-Laufzeit",
"runtime.use_default": "Standard-Laufzeit verwenden",
"runtime.unavailable": "{{name}} (nicht verfügbar)",
- "runtime.separate_prefix": "Separates Präfix für diese Laufzeitfamilie verwenden",
- "runtime.prefix_warning": "Updates innerhalb dieser Laufzeitfamilie verwenden dasselbe Präfix und dieselben lokalen Spielstände. Beim Wechsel der Familie wird ein separates Präfix verwendet. Vorhandene lokale Spielstände bleiben im alten Präfix und werden nicht automatisch kopiert oder übertragen.",
"auth.browser": "Im Browser fortfahren",
"auth.browser_error": "Die Anmeldung konnte nicht im Browser geöffnet werden. Google Chrome muss installiert sein. Versuche es erneut oder wähle eine andere Methode.",
"auth.cancel_passkey": "Passkey Abfrage abbrechen",
diff --git a/assets/locales/en.json b/assets/locales/en.json
index 1e37d49..2233a0d 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -46,8 +46,6 @@
"runtime.game_runtime": "Game runtime",
"runtime.use_default": "Use default runtime",
"runtime.unavailable": "{{name}} (unavailable)",
- "runtime.separate_prefix": "Use a separate prefix for this runtime family",
- "runtime.prefix_warning": "Updates within this family reuse the same prefix and local saves. Switching families uses a separate prefix. Existing local saves stay in the old prefix and are not copied or transferred automatically.",
"library.stop_update_check": "Stop checking updates",
"notifications.title": "Notifications",
"notifications.unread_one": "Notifications, {{count}} unread",
diff --git a/assets/locales/es.json b/assets/locales/es.json
index b881a41..b5ceff6 100644
--- a/assets/locales/es.json
+++ b/assets/locales/es.json
@@ -2,8 +2,6 @@
"runtime.game_runtime": "Entorno del juego",
"runtime.use_default": "Usar el entorno predeterminado",
"runtime.unavailable": "{{name}} (no disponible)",
- "runtime.separate_prefix": "Usar un prefijo independiente para esta familia de entornos",
- "runtime.prefix_warning": "Las actualizaciones de esta familia reutilizan el mismo prefijo y las partidas locales. Cambiar de familia usa un prefijo independiente. Las partidas existentes permanecen en el prefijo anterior y no se copian ni transfieren automáticamente.",
"auth.browser": "Continuar en el navegador",
"auth.browser_error": "No se ha podido abrir el inicio de sesión en el navegador. Google Chrome debe estar instalado. Inténtalo de nuevo o elige otro método.",
"auth.cancel_passkey": "Cancelar solicitud de llave de acceso",
diff --git a/assets/locales/fr.json b/assets/locales/fr.json
index ab87f0d..1d39993 100644
--- a/assets/locales/fr.json
+++ b/assets/locales/fr.json
@@ -2,8 +2,6 @@
"runtime.game_runtime": "Environnement du jeu",
"runtime.use_default": "Utiliser l’environnement par défaut",
"runtime.unavailable": "{{name}} (indisponible)",
- "runtime.separate_prefix": "Utiliser un préfixe séparé pour cette famille d’environnements",
- "runtime.prefix_warning": "Les mises à jour de cette famille réutilisent le même préfixe et les sauvegardes locales. Changer de famille utilise un préfixe séparé. Les sauvegardes existantes restent dans l’ancien préfixe et ne sont ni copiées ni transférées automatiquement.",
"auth.browser": "Continuer dans le navigateur",
"auth.browser_error": "Impossible d'ouvrir la connexion dans le navigateur. Google Chrome doit être installé. Réessayez ou choisissez une autre méthode.",
"auth.passkey_label": "Aide pour la clé d'accès de Nexus Launcher",
diff --git a/assets/locales/it.json b/assets/locales/it.json
index 522d793..638c97d 100644
--- a/assets/locales/it.json
+++ b/assets/locales/it.json
@@ -2,8 +2,6 @@
"runtime.game_runtime": "Ambiente del gioco",
"runtime.use_default": "Usa l’ambiente predefinito",
"runtime.unavailable": "{{name}} (non disponibile)",
- "runtime.separate_prefix": "Usa un prefisso separato per questa famiglia di ambienti",
- "runtime.prefix_warning": "Gli aggiornamenti di questa famiglia riutilizzano lo stesso prefisso e i salvataggi locali. Cambiare famiglia usa un prefisso separato. I salvataggi esistenti restano nel vecchio prefisso e non vengono copiati o trasferiti automaticamente.",
"auth.browser": "Continua nel browser",
"auth.browser_error": "Impossibile aprire il browser per accedere. Google Chrome deve essere installato. Prova di nuovo o scegli un altro metodo.",
"auth.cancel_passkey": "Annulla la richiesta di passkey",
diff --git a/assets/locales/pl-PL.json b/assets/locales/pl-PL.json
index cb6b57e..dca04d2 100644
--- a/assets/locales/pl-PL.json
+++ b/assets/locales/pl-PL.json
@@ -2,8 +2,6 @@
"runtime.game_runtime": "Środowisko gry",
"runtime.use_default": "Użyj domyślnego środowiska",
"runtime.unavailable": "{{name}} (niedostępne)",
- "runtime.separate_prefix": "Użyj osobnego prefiksu dla tej rodziny środowisk",
- "runtime.prefix_warning": "Aktualizacje tej rodziny używają tego samego prefiksu i lokalnych zapisów. Zmiana rodziny używa osobnego prefiksu. Istniejące zapisy pozostają w starym prefiksie i nie są automatycznie kopiowane ani przenoszone.",
"common.view_all": "Pokaż wszystkie ({{count}})",
"downloads.active_summary": "Kolejka instalacji, instalacje w toku: {{count}}, {{state}}, {{game}}",
"downloads.current": "{{state}} ({{current}}/{{total}})",
diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json
index c66931c..0ce15bc 100644
--- a/assets/locales/pt-BR.json
+++ b/assets/locales/pt-BR.json
@@ -2,8 +2,6 @@
"runtime.game_runtime": "Ambiente do jogo",
"runtime.use_default": "Usar o ambiente padrão",
"runtime.unavailable": "{{name}} (indisponível)",
- "runtime.separate_prefix": "Usar um prefixo separado para esta família de ambientes",
- "runtime.prefix_warning": "As atualizações desta família reutilizam o mesmo prefixo e os salvamentos locais. Mudar de família usa um prefixo separado. Os salvamentos existentes permanecem no prefixo antigo e não são copiados ou transferidos automaticamente.",
"auth.browser": "Continuar no navegador",
"auth.browser_error": "Não foi possível abrir o login no navegador. O Google Chrome precisa estar instalado. Tente novamente ou escolha outro método.",
"auth.cancel_passkey": "Cancelar solicitação de chave de acesso",
diff --git a/assets/locales/zh-CN.json b/assets/locales/zh-CN.json
index 56c9ee0..7193cdc 100644
--- a/assets/locales/zh-CN.json
+++ b/assets/locales/zh-CN.json
@@ -2,8 +2,6 @@
"runtime.game_runtime": "游戏运行环境",
"runtime.use_default": "使用默认运行环境",
"runtime.unavailable": "{{name}}(不可用)",
- "runtime.separate_prefix": "为此运行环境系列使用独立前缀",
- "runtime.prefix_warning": "同一系列的更新会继续使用相同的前缀和本地存档。切换系列会使用独立前缀。现有本地存档保留在旧前缀中,不会自动复制或转移。",
"auth.browser": "在浏览器中继续",
"auth.browser_error": "未能打开浏览器登录页面。必须安装Google Chrome。请重试或选择其他方式。",
"auth.cancel_passkey": "取消通行密钥请求",
diff --git a/assets/locales/zh-Hant.json b/assets/locales/zh-Hant.json
index dcffe8f..254fa2e 100644
--- a/assets/locales/zh-Hant.json
+++ b/assets/locales/zh-Hant.json
@@ -2,8 +2,6 @@
"runtime.game_runtime": "遊戲執行環境",
"runtime.use_default": "使用預設執行環境",
"runtime.unavailable": "{{name}}(無法使用)",
- "runtime.separate_prefix": "為此執行環境系列使用獨立前綴",
- "runtime.prefix_warning": "同一系列的更新會繼續使用相同的前綴和本機存檔。切換系列會使用獨立前綴。現有本機存檔保留在舊前綴中,不會自動複製或轉移。",
"auth.browser": "在瀏覽器中繼續",
"auth.browser_error": "無法開啟瀏覽器登入。必須已安裝 Google Chrome。請重試或選擇其他方式。",
"auth.cancel_passkey": "取消金鑰(Passkey)請求",
diff --git a/scripts/RUNTIME_FAMILIES.md b/scripts/RUNTIME_FAMILIES.md
index 716263e..2730d3c 100644
--- a/scripts/RUNTIME_FAMILIES.md
+++ b/scripts/RUNTIME_FAMILIES.md
@@ -37,14 +37,22 @@ build. Every new launch resolves the current family receipt and uses it
directly. The existing prefix and local saves are reused in place. No migration,
copy, transfer or prefix initialization occurs when saving the selection.
-Selecting a family for the first time requires an explicit separate-prefix
-choice; changing family is a separate explicit choice. New family prefixes live
-under `runtime-prefixes/<family>/prefixes/<gameId>/`. Pre-0.5 build-bound
-prefixes remain under `runtime-prefixes/<family>/<buildId>/<gameId>/` and are
-preserved by their recorded build origin as prefix anchors, not as runtime
-selections. The default family keeps `compatdata/<gameId>` and
-`prefixes/<gameId>`. Unknown or mismatched prefix bindings fail closed, and a
-nonempty unbound prefix is never adopted.
+A game's prefix location is a durable backend-owned identity stored with the
+game record (`runtimePrefixIdentity`). It is captured from the location that the
+persisted selection already used, so changing family or updating a family build
+selects only the verified runner: no separate-prefix consent, copy, reset, merge
+or save migration is involved. A game without an existing prefix uses the
+canonical per-game location `compatdata/<gameId>`, with `prefixes/<gameId>` for
+its plain Wine root, independent of the chosen family. Existing family and build
+prefixes keep their exact paths under `runtime-prefixes/<family>/prefixes/<gameId>/`
+and `runtime-prefixes/<family>/<buildId>/<gameId>/`, bound by their recorded
+origin rather than by the current family. Unknown, partial or mismatched bindings
+and unbound nonempty experimental prefixes fail closed for every runner.
+Symlinked prefixes or binding files are refused on experimental layouts with any
+runner and on the canonical prefix with a managed runner; the pre-0.5 canonical
+default prefix keeps its existing behaviour. A legacy history with several
+existing prefixes that the persisted record does not select is refused as well,
+with every prefix and save preserved and nothing merged.
## Session rules
diff --git a/src/main/game-runtime-readiness.ts b/src/main/game-runtime-readiness.ts
index 9d33264..ed624e0 100644
--- a/src/main/game-runtime-readiness.ts
+++ b/src/main/game-runtime-readiness.ts
@@ -1,12 +1,12 @@
import type {Game} from '../shared/types.js';
-import {resolveGameRuntime} from './runtime-prefix-binding.js';
+import {gameRuntimeParameters,resolveGameRuntime} from './runtime-prefix-binding.js';
export interface RuntimeReadinessState {
- game?:Pick<Game,'id'|'runtime'|'runtimeSeparatePrefix'|'runtimeBuild'|'runtimePrefixes'>;
+ game?:Pick<Game,'id'|'runtime'|'runtimeSeparatePrefix'|'runtimeBuild'|'runtimePrefixes'|'runtimePrefixIdentity'>;
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,game?.runtimePrefixes,state.runtimeRoot,state.dataRoot,state.defaultWine,state.arch]);
+ return JSON.stringify([game?.id,game?.runtime,game?.runtimePrefixIdentity,game?.runtimeSeparatePrefix,game?.runtimeBuild?.buildId,game?.runtimeBuild?.manifestSha256,game?.runtimeBuild?.sourceCommit,game?.runtimePrefixes,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. */
@@ -14,7 +14,7 @@ export async function gameRuntimeReadiness(read:()=>RuntimeReadinessState,resolv
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,prefixAnchor:state.game.runtime&&state.game.runtime!=='default'?state.game.runtimePrefixes?.[state.game.runtime]:undefined,defaultWine:state.defaultWine,arch:state.arch});
+ await resolve({runtimeRoot:state.runtimeRoot,dataRoot:state.dataRoot,defaultWine:state.defaultWine,arch:state.arch,...gameRuntimeParameters(state.game)});
return before===identity(read());
}catch{return false;}
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 2b894f0..fce8ab9 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -2,9 +2,9 @@ import { ComponentUpdateAdmission, type ComponentUpdateOwner } from './component
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 {guardedRuntimeSettings,type RuntimeSettingsRequest} from './runtime-settings.js';
import {gameRuntimeSelection} from '../shared/runtime-selection.js';
-import {resolveGameRuntime,bindRuntimePrefix} from './runtime-prefix-binding.js';
+import {resolveGameRuntime,bindRuntimePrefix,gameRuntimeParameters} from './runtime-prefix-binding.js';
import {desktopTrayAvailable} from './launcher-tray-desktop.js';
import {LauncherTray} from './launcher-tray.js';
import {SteamKeyboard} from './steam-keyboard.js';
@@ -870,8 +870,7 @@ async function gameContent(id: string) {
if (authState.running || authState.stored !== true) throw Error('Sign in before checking game content.');
const identity = `${authState.username}:${backend.current.binaryPath}:${currentMarket()}`;
accountLibrary.select(authState.username, backend.current.capabilities.library ? backend.current.binaryPath : undefined, currentMarket());
- const selectedRuntime=await resolveGameRuntime({runtimeRoot:store.settings.runtimeRoot,dataRoot:path.dirname(store.settings.runtimeRoot),gameId:game.id,
- selection:game.runtime,separatePrefix:game.runtimeSeparatePrefix,approvedBuild:game.runtimeBuild,prefixAnchor:game.runtime&&game.runtime!=='default'?game.runtimePrefixes?.[game.runtime]:undefined,defaultWine:selectedWinePath(store.settings.winePath,store.settings.runtimeRoot,runtime.current.winePath)});
+ const selectedRuntime=await resolveGameRuntime({runtimeRoot:store.settings.runtimeRoot,dataRoot:path.dirname(store.settings.runtimeRoot),defaultWine:selectedWinePath(store.settings.winePath,store.settings.runtimeRoot,runtime.current.winePath),...gameRuntimeParameters(game)});
const result = await contentManager().plan(game, () => accountLibrary.access(true), currentMarket());
const wine = selectedRuntime.winePath;
result.plan.runtimeSupported = Boolean(wine && await storeContentRuntime(wine));
@@ -1209,8 +1208,7 @@ async function gameLaunchOptions(id: string): Promise<GameLaunchOptions> {
if (!game) throw new Error('Game not found.');
let wine: string;
try {
- wine=(await resolveGameRuntime({runtimeRoot:store.settings.runtimeRoot,dataRoot:path.dirname(store.settings.runtimeRoot),gameId:game.id,
- selection:game.runtime,separatePrefix:game.runtimeSeparatePrefix,approvedBuild:game.runtimeBuild,prefixAnchor:game.runtime&&game.runtime!=='default'?game.runtimePrefixes?.[game.runtime]:undefined,defaultWine:selectedWinePath(store.settings.winePath,store.settings.runtimeRoot,runtime.current.winePath)})).winePath;
+ wine=(await resolveGameRuntime({runtimeRoot:store.settings.runtimeRoot,dataRoot:path.dirname(store.settings.runtimeRoot),defaultWine:selectedWinePath(store.settings.winePath,store.settings.runtimeRoot,runtime.current.winePath),...gameRuntimeParameters(game)})).winePath;
} catch(error) { const reason=(error as Error).message;return {cloudSaves:false,cloudReason:reason,vcInstall:false,vcReason:reason}; }
if (!wine) return { cloudSaves: false, cloudReason: 'Select Xodus Runtime in Settings.', vcInstall: false, vcReason: 'Select Xodus Runtime in Settings.' };
const wineAvailable = await fs.access(wine, constants.X_OK).then(() => true, () => false);
@@ -1292,8 +1290,7 @@ async function prepareGameLaunch(id: string, steam?: SteamGameContext): Promise<
if (inspected.installState !== 'ready') throw new Error(inspected.installMessage ?? 'The installation is not ready for Xodus run.');
const locale = supportedGameLocale(game.locale ?? '');
const titleId = await gameTitleId(game).catch(() => undefined);
- const runtimeContext = await resolveGameRuntime({runtimeRoot:store.settings.runtimeRoot,dataRoot:path.dirname(store.settings.runtimeRoot),gameId:game.id,
- selection:game.runtime,separatePrefix:game.runtimeSeparatePrefix,approvedBuild:game.runtimeBuild,prefixAnchor:game.runtime&&game.runtime!=='default'?game.runtimePrefixes?.[game.runtime]:undefined,defaultWine:selectedWinePath(store.settings.winePath,store.settings.runtimeRoot,runtime.current.winePath)});
+ const runtimeContext = await resolveGameRuntime({runtimeRoot:store.settings.runtimeRoot,dataRoot:path.dirname(store.settings.runtimeRoot),defaultWine:selectedWinePath(store.settings.winePath,store.settings.runtimeRoot,runtime.current.winePath),...gameRuntimeParameters(game)});
const wine = runtimeContext.winePath;
await bindRuntimePrefix(runtimeContext);
if (!wine) throw new Error('Select a Wine / Proton binary in Settings.');
@@ -1601,8 +1598,7 @@ async function installGameVcRuntime(id: string): Promise<void> {
if (!game) throw new Error('Game not found.');
const inspected = await inspectGameDirectory(game.path);
if (inspected.installState !== 'ready') throw new Error(inspected.installMessage ?? 'The game installation is not ready.');
- const runtimeContext = await resolveGameRuntime({runtimeRoot:store.settings.runtimeRoot,dataRoot:path.dirname(store.settings.runtimeRoot),gameId:game.id,
- selection:game.runtime,separatePrefix:game.runtimeSeparatePrefix,approvedBuild:game.runtimeBuild,prefixAnchor:game.runtime&&game.runtime!=='default'?game.runtimePrefixes?.[game.runtime]:undefined,defaultWine:selectedWinePath(store.settings.winePath,store.settings.runtimeRoot,runtime.current.winePath)});
+ const runtimeContext = await resolveGameRuntime({runtimeRoot:store.settings.runtimeRoot,dataRoot:path.dirname(store.settings.runtimeRoot),defaultWine:selectedWinePath(store.settings.winePath,store.settings.runtimeRoot,runtime.current.winePath),...gameRuntimeParameters(game)});
const wine = runtimeContext.winePath;
await bindRuntimePrefix(runtimeContext);
if (!wine) throw new Error('Select Xodus Runtime in Settings first.');
@@ -2168,13 +2164,6 @@ function registerIpc(): void {
ipcMain.handle('runtime-families', async () => {const families=await runtime.refreshFamilies();emitSnapshot();return families;});
ipcMain.handle('update-game', async (_event, id: string, patch: Partial<Game>&RuntimeSettingsRequest) => {
const allowed: Partial<Game> = {};
- if ('runtime' in patch || 'runtimeSeparatePrefix' in patch) {
- const current=store.games.find(game=>game.id===id);
- if(!current)throw Error('Game not found.');
- const selection=gameRuntimeSelection('runtime' in patch?patch.runtime:current.runtime);
- if(selection!==(current.runtime??'default')||selection!=='default'&&patch.runtimeSeparatePrefix!==undefined&&patch.runtimeSeparatePrefix!==current.runtimeSeparatePrefix)ensureIdle();
- Object.assign(allowed,await approvedRuntimeSettings(current,patch,store.settings.runtimeRoot));
- }
for (const key of ['title', 'executable', 'launchArgs'] as const) if (typeof patch[key] === 'string') allowed[key] = patch[key];
if ('launchTools' in patch) allowed.launchTools = normalizeLaunchTools(patch.launchTools);
if (typeof patch.locale === 'string') {
@@ -2182,7 +2171,23 @@ function registerIpc(): void {
if (!game) throw new Error('Game not found.');
allowed.locale = supportedGameLocale(patch.locale) ?? '';
}
- const game = await store.patchGame(id, allowed);
+ let game: Game;
+ if ('runtime' in patch || 'runtimeSeparatePrefix' in patch) {
+ const current=store.games.find(entry=>entry.id===id);
+ if(!current)throw Error('Game not found.');
+ const snapshot=structuredClone(current);
+ const changing=gameRuntimeSelection('runtime' in patch?patch.runtime:snapshot.runtime)!==gameRuntimeSelection(snapshot.runtime);
+ // A real family change holds the activity slot through verification and the
+ // persisted write, so no launch or component update can enter in between.
+ game=await guardedRuntimeSettings({current:snapshot,request:patch,
+ paths:{runtimeRoot:store.settings.runtimeRoot,dataRoot:path.dirname(store.settings.runtimeRoot)},changing,
+ reserve:()=>{
+ const owner=componentUpdateAdmission.reserve();
+ return {admit:()=>ensureIdle(undefined,undefined,owner),release:()=>componentUpdateAdmission.release(owner)};
+ },
+ read:()=>store.games.find(entry=>entry.id===id),
+ persist:(runtime)=>store.patchGame(id,{...allowed,...runtime})});
+ } else game=await store.patchGame(id, allowed);
emitSnapshot();
return game;
});
diff --git a/src/main/runtime-families.test.ts b/src/main/runtime-families.test.ts
index 4f88a3d..2de88d0 100644
--- a/src/main/runtime-families.test.ts
+++ b/src/main/runtime-families.test.ts
@@ -5,15 +5,17 @@ import path from 'node:path';
import os from 'node:os';
import {execFile as execFileCallback} from 'node:child_process';
import {promisify} from 'node:util';
-import {approvedRuntimeSettings} from './runtime-settings';
+import {approvedRuntimeSettings,guardedRuntimeSettings,type RuntimeSettingsRequest,type RuntimeSettingsPaths} from './runtime-settings';
import type {Game} from '../shared/types';
import {prepareProtonRunner} from './proton';
import {createHash} from 'node:crypto';
import {resolveRuntimeFamily,resolveRuntimeFamilyBuild,retainRuntimeFamilyBuild,installedRuntimeFamilies,runtimeFamilyVerificationStats} from './runtime-families';
-import {resolveGameRuntime,bindRuntimePrefix} from './runtime-prefix-binding';
-import {gameRuntimeSelection} from '../shared/runtime-selection';
+import {resolveGameRuntime,bindRuntimePrefix,captureGamePrefixIdentity,gameRuntimeParameters} from './runtime-prefix-binding';
+import {gameRuntimeAvailable,gameRuntimeSelection,runtimePrefixIdentity} from '../shared/runtime-selection';
let root:string,release:string;
const hash=(value:string|Buffer)=>createHash('sha256').update(value).digest('hex');
+const digest=async(file:string)=>hash(await fs.readFile(file));
+const present=async(file:string)=>fs.access(file).then(()=>true,()=>false);
async function approval(){const value=JSON.parse(await fs.readFile(path.join(root,'variants',family,'current.json'),'utf8'));return {buildId:value.buildId,manifestSha256:value.manifestSha256,sourceCommit:value.sourceCommit};}
const family='nexus-cachyos',buildId='b'.repeat(64),sourceCommit='a'.repeat(40),sourceRepository='domsvoboda/nexus-runtime-cachyos';
async function fixture() {
@@ -29,7 +31,34 @@ async function fixture() {
await fs.writeFile(path.join(release,'nexus-family.json'),manifest);
await fs.writeFile(path.join(root,'variants',family,'current.json'),JSON.stringify({schema:1,family,buildId,sourceRepository,sourceCommit,manifestSha256:hash(manifest)}));
}
-beforeEach(async()=>{root=await fs.mkdtemp(path.join(os.tmpdir(),'runtime-family-test-'));release=path.join(root,'variants',family,'releases',buildId);await fs.mkdir(release,{recursive:true});});
+/** Copies the verified fixture to the other managed family so both family
+ * runners are installed and verifiable in the same data root. */
+async function secondFamily(id:'nexus'|'nexus-cachyos'='nexus') {
+ const repository='domsvoboda/nexus-runtime';
+ const directory=path.join(root,'variants',id);await fs.cp(path.join(root,'variants',family),directory,{recursive:true});
+ const manifestFile=path.join(directory,'releases',buildId,'nexus-family.json');
+ const manifest=JSON.parse(await fs.readFile(manifestFile,'utf8'));manifest.family=id;manifest.sourceRepository=repository;
+ const bytes=JSON.stringify(manifest);await fs.writeFile(manifestFile,bytes);
+ await fs.writeFile(path.join(directory,'current.json'),JSON.stringify({schema:1,family:id,buildId,sourceRepository:repository,sourceCommit,manifestSha256:hash(bytes)}));
+ return path.join(directory,'releases',buildId,'files/bin/wine');
+}
+/** Pre-0.5 family-wide experimental prefix with its exact legacy marker. */
+async function legacyFamilyPrefix(gameId:string,id:'nexus'|'nexus-cachyos'=family) {
+ const rootPath=path.join(root,'runtime-prefixes',id,'prefixes',gameId),compatibilityDataPath=path.join(rootPath,'compatdata');
+ await fs.mkdir(compatibilityDataPath,{recursive:true});
+ await fs.writeFile(path.join(compatibilityDataPath,'.nexus-runtime-family.json'),JSON.stringify({schema:2,layout:'family',family:id,prefixSchema:1,arch:'x64'}));
+ await fs.writeFile(path.join(compatibilityDataPath,'save'),`${id} progress`);
+ return {compatibilityDataPath,legacyPrefixRoot:path.join(rootPath,'wine')};
+}
+/** Pre-0.5 build-specific experimental prefix with its exact legacy marker. */
+async function legacyBuildPrefix(gameId:string,origin:{buildId:string;sourceCommit:string;manifestSha256:string},id:'nexus'|'nexus-cachyos'=family) {
+ const compatibilityDataPath=path.join(root,'runtime-prefixes',id,origin.buildId,gameId,'compatdata');
+ await fs.mkdir(compatibilityDataPath,{recursive:true});
+ await fs.writeFile(path.join(compatibilityDataPath,'.nexus-runtime-family.json'),JSON.stringify({schema:1,family:id,buildId:origin.buildId,sourceCommit:origin.sourceCommit,manifestSha256:origin.manifestSha256,prefixSchema:1,arch:'x64'}));
+ await fs.writeFile(path.join(compatibilityDataPath,'save'),'legacy build progress');
+ return {compatibilityDataPath};
+}
+beforeEach(async()=>{root=await fs.mkdtemp(path.join(os.tmpdir(),'runtime-family-test-'));paths={runtimeRoot:root,dataRoot:root};release=path.join(root,'variants',family,'releases',buildId);await fs.mkdir(release,{recursive:true});});
afterEach(async()=>{await fs.rm(root,{recursive:true,force:true});});
it('accepts only known IDs, defaults only an absent preference, rejects hostile persisted values',()=>{
expect(gameRuntimeSelection(undefined)).toBe('default');
@@ -53,50 +82,361 @@ it('rejects executable symlink redirection even to matching bytes',async()=>{
await expect(resolveRuntimeFamily(root,family,'x64')).rejects.toThrow();
});
it('captures immutable independent sessions and preserves the default prefix path',async()=>{
- await fixture();const options={runtimeRoot:root,dataRoot:root,gameId:'test',defaultWine:'/default/wine',arch:'x64',approvedBuild:await approval()};
- const legacy=await resolveGameRuntime({...options,selection:undefined,separatePrefix:false});
- const variant=await resolveGameRuntime({...options,selection:family,separatePrefix:true});
+ await fixture();const options={runtimeRoot:root,dataRoot:root,gameId:'test',defaultWine:'/default/wine',arch:'x64'};
+ const legacy=await resolveGameRuntime({...options,selection:undefined});
+ const variant=await resolveGameRuntime({...options,selection:family});
expect(legacy.compatibilityDataPath).toBe(path.join(root,'compatdata','test'));
- expect(variant.compatibilityDataPath).toContain(path.join('runtime-prefixes',family,buildId));
+ // A game without an existing prefix resolves the same per-game location for every family.
+ expect(variant.compatibilityDataPath).toBe(legacy.compatibilityDataPath);
expect(Object.isFrozen(variant)).toBe(true);expect(Object.isFrozen(variant.managed)).toBe(true);
+ expect(variant.winePath).toBe(path.join(release,'files/bin/wine'));
await fs.unlink(path.join(root,'variants',family,'current.json'));
expect(variant.winePath).toBe(path.join(release,'files/bin/wine'));
- await expect(resolveGameRuntime({...options,selection:family,separatePrefix:true})).rejects.toThrow();
-});
-it('requires explicit separate prefix consent without mutating the legacy prefix or copying saves',async()=>{
- await fixture();await fs.mkdir(path.join(root,'compatdata','test'),{recursive:true});await fs.writeFile(path.join(root,'compatdata','test','save'),'original');
- const options={runtimeRoot:root,dataRoot:root,gameId:'test',selection:family,defaultWine:'/default/wine',arch:'x64',approvedBuild:await approval()};
- await expect(resolveGameRuntime({...options,separatePrefix:false})).rejects.toThrow('local saves');
- const context=await resolveGameRuntime({...options,separatePrefix:true});await bindRuntimePrefix(context);
- expect(await fs.readdir(context.compatibilityDataPath)).toEqual(['.nexus-runtime-family.json']);
- expect(await fs.readFile(path.join(root,'compatdata','test','save'),'utf8')).toBe('original');
+ await expect(resolveGameRuntime({...options,selection:family})).rejects.toThrow();
+});
+it('chooses a managed family without separate-prefix consent and never touches the legacy prefix',async()=>{
+ await fixture();const canonical=path.join(root,'compatdata','test');
+ await fs.mkdir(canonical,{recursive:true});await fs.writeFile(path.join(canonical,'save'),'original');
+ const game=savedGame();
+ const patch=await approve(game,{runtime:family,runtimeSeparatePrefix:false});
+ expect(patch.runtimePrefixIdentity).toEqual({layout:'game'});
+ expect(patch.runtimeSeparatePrefix).toBeUndefined();
+ const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(game)});
+ expect(context.compatibilityDataPath).toBe(canonical);
+ await bindRuntimePrefix(context);await bindRuntimePrefix(context);
+ // A pre-0.5 default prefix is preserved unbound: no marker is invented for it.
+ expect(await present(path.join(canonical,'.nexus-runtime-family.json'))).toBe(false);
+ expect(await fs.readFile(path.join(canonical,'save'),'utf8')).toBe('original');
+ expect(await present(path.join(root,'runtime-prefixes'))).toBe(false);
+ await expect(approve(game,{runtime:family,runtimeSeparatePrefix:'yes' as never})).rejects.toThrow('Invalid');
+});
+it('keeps one stable per-game prefix and byte-identical saves across default, CachyOS and Standard',async()=>{
+ await fixture();const standardRelease=await secondFamily('nexus');
+ let game=savedGame();
+ const context=async()=>resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(game)});
+ // The first managed run creates the canonical prefix and records its contract.
+ Object.assign(game,await approve(game,{runtime:family}));
+ const first=await context();expect(first.compatibilityDataPath).toBe(path.join(root,'compatdata','test'));
+ await bindRuntimePrefix(first);
+ const marker=path.join(first.compatibilityDataPath,'.nexus-runtime-family.json');
+ const markerBytes=await fs.readFile(marker,'utf8');
+ expect(JSON.parse(markerBytes)).toMatchObject({schema:3,layout:'game',gameId:'test'});
+ const save=path.join(first.compatibilityDataPath,'pfx/drive_c/save');await fs.mkdir(path.dirname(save),{recursive:true});await fs.writeFile(save,'synthetic progress');
+ const originalBytes=await digest(save),inode=(await fs.stat(save)).ino;
+ for(const choice of ['default',family,'nexus','default',family] as const) {
+ Object.assign(game,await approve(game,{runtime:choice}));
+ const current=await context();await bindRuntimePrefix(current);
+ expect(current.compatibilityDataPath).toBe(first.compatibilityDataPath);
+ expect(await digest(save)).toBe(originalBytes);
+ expect((await fs.stat(save)).ino).toBe(inode);
+ // The origin marker is never rewritten or invalidated by a family switch.
+ expect(await fs.readFile(marker,'utf8')).toBe(markerBytes);
+ expect(current.winePath).toBe(choice==='default'?'/default/wine':choice==='nexus'?standardRelease:path.join(release,'files/bin/wine'));
+ }
+ expect(game.runtimePrefixIdentity).toEqual({layout:'game'});
+ expect(await present(path.join(root,'runtime-prefixes'))).toBe(false);
+ const {StateStore}=await import('./store');const store=new StateStore(path.join(root,'profile'));
+ await store.upsertGame(game);const loaded=new StateStore(path.join(root,'profile'));await loaded.load();
+ expect(loaded.games[0].runtimePrefixIdentity).toEqual({layout:'game'});
+});
+it('keeps an existing legacy family prefix at its exact path and marker through another family, default and back',async()=>{
+ await fixture();const standardRelease=await secondFamily('nexus');
+ const origin=await approval(),legacy=await legacyBuildPrefix('test',origin);
+ let game={...savedGame(),runtime:family,runtimeBuild:origin} as Game;
+ const context=async()=>resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(game)});
+ const first=await context();expect(first.compatibilityDataPath).toBe(legacy.compatibilityDataPath);
+ await bindRuntimePrefix(first);
+ const marker=path.join(legacy.compatibilityDataPath,'.nexus-runtime-family.json');
+ const markerBytes=await fs.readFile(marker,'utf8'),saveBytes=await digest(path.join(legacy.compatibilityDataPath,'save'));
+ Object.assign(game,await approve(game,{runtime:'nexus'}));
+ expect(game.runtimePrefixIdentity).toEqual({layout:'build',family,origin});expect(game.runtimeBuild).toBeUndefined();
+ const other=await context();await bindRuntimePrefix(other);
+ expect(other.compatibilityDataPath).toBe(legacy.compatibilityDataPath);expect(other.winePath).toBe(standardRelease);
+ Object.assign(game,await approve(game,{runtime:'default'}));
+ const canonical=await context();await bindRuntimePrefix(canonical);
+ expect(canonical.compatibilityDataPath).toBe(legacy.compatibilityDataPath);expect(canonical.winePath).toBe('/default/wine');
+ Object.assign(game,await approve(game,{runtime:family}));
+ const back=await context();await bindRuntimePrefix(back);
+ expect(back.compatibilityDataPath).toBe(legacy.compatibilityDataPath);
+ expect(await fs.readFile(marker,'utf8')).toBe(markerBytes);
+ expect(await digest(path.join(legacy.compatibilityDataPath,'save'))).toBe(saveBytes);
+ // No family-specific or canonical copy is created next to the preserved prefix.
+ expect(await present(path.join(root,'compatdata'))).toBe(false);
+ const {StateStore}=await import('./store');const store=new StateStore(path.join(root,'profile'));
+ await store.upsertGame(game);
+ const loaded=new StateStore(path.join(root,'profile'));await loaded.load();
+ expect(loaded.games[0].runtimePrefixIdentity).toEqual({layout:'build',family,origin});
+});
+it('reuses the pre-0.5 legacy default prefix for a managed family without moving or rewriting it',async()=>{
+ await fixture();const canonical=path.join(root,'compatdata','test');
+ await fs.mkdir(path.join(canonical,'pfx'),{recursive:true});await fs.writeFile(path.join(canonical,'pfx/save'),'legacy progress');
+ const originalBytes=await digest(path.join(canonical,'pfx/save'));
+ const game=savedGame();
+ const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(game)});
+ expect(context.compatibilityDataPath).toBe(canonical);
await bindRuntimePrefix(context);
- await fs.writeFile(path.join(context.compatibilityDataPath,'.nexus-runtime-family.json'),'{}');
- await expect(bindRuntimePrefix(context)).rejects.toThrow('mismatch');
+ expect(await present(path.join(canonical,'.nexus-runtime-family.json'))).toBe(false);
+ expect(await digest(path.join(canonical,'pfx/save'))).toBe(originalBytes);
+ const patch=await approve(game,{runtime:family});
+ expect(patch.runtimePrefixIdentity).toEqual({layout:'game'});
});
-it('does not adopt an unbound experimental prefix or another family in the default path',async()=>{
- await fixture();const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:'test',selection:family,separatePrefix:true,approvedBuild:await approval(),defaultWine:'/default/wine',arch:'x64'});
- await fs.mkdir(context.compatibilityDataPath,{recursive:true});await fs.writeFile(path.join(context.compatibilityDataPath,'save'),'keep');
- await expect(bindRuntimePrefix(context)).rejects.toThrow('no runtime binding');
- const legacy=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:'test',selection:'default',separatePrefix:false,defaultWine:'/default/wine'});
- await fs.mkdir(legacy.compatibilityDataPath,{recursive:true});await fs.writeFile(path.join(legacy.compatibilityDataPath,'.nexus-runtime-family.json'),JSON.stringify({family}));
- await expect(bindRuntimePrefix(legacy)).rejects.toThrow('another runtime');
+it('does not adopt an unbound experimental prefix and rejects a foreign binding on the per-game prefix',async()=>{
+ await fixture();
+ const legacy=await legacyFamilyPrefix('test'),marker=path.join(legacy.compatibilityDataPath,'.nexus-runtime-family.json');
+ await fs.unlink(marker);
+ // The selection owns this exact directory, so it is resolved but its missing
+ // binding is never adopted and its files are preserved.
+ const adopted=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'test',selection:family,runtimePrefixes:{[family]:{layout:'family'}}});
+ expect(adopted.compatibilityDataPath).toBe(legacy.compatibilityDataPath);
+ await expect(bindRuntimePrefix(adopted)).rejects.toThrow('no runtime binding');
+ expect(await fs.readFile(path.join(legacy.compatibilityDataPath,'save'),'utf8')).toBe(`${family} progress`);
+ const canonical=path.join(root,'compatdata','other');await fs.mkdir(canonical,{recursive:true});
+ await fs.writeFile(path.join(canonical,'.nexus-runtime-family.json'),JSON.stringify({schema:2,layout:'family',family}));
+ const perGame=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'other',selection:family});
+ await expect(bindRuntimePrefix(perGame)).rejects.toThrow('mismatch');
+});
+it('rejects legacy bindings with a missing, partial or malformed prefix contract',async()=>{
+ await fixture();const origin=await approval(),legacy=await legacyBuildPrefix('test',origin);
+ const marker=path.join(legacy.compatibilityDataPath,'.nexus-runtime-family.json');
+ const base=JSON.parse(await fs.readFile(marker,'utf8'));
+ const invalid:Record<string,unknown>[]=[];
+ const missing={...base};delete missing.prefixSchema;delete missing.arch;invalid.push(missing);
+ invalid.push({...base,arch:undefined});
+ invalid.push({...base,prefixSchema:undefined});
+ invalid.push({...base,prefixSchema:'1'});
+ invalid.push({...base,prefixSchema:0});
+ invalid.push({...base,prefixSchema:1.5});
+ invalid.push({...base,arch:''});
+ invalid.push({...base,arch:42});
+ invalid.push({...base,arch:['x64']});
+ invalid.push({...base,arch:null});
+ invalid.push(null as never);
+ invalid.push([] as never);
+ invalid.push('binding' as never);
+ for(const forged of invalid) {
+ await fs.writeFile(marker,JSON.stringify(forged));
+ const bytes=await fs.readFile(marker,'utf8');
+ const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'test',selection:family,runtimeBuild:origin});
+ await expect(bindRuntimePrefix(context)).rejects.toThrow('mismatch');
+ expect(await fs.readFile(marker,'utf8')).toBe(bytes);
+ }
+ // A well-formed legacy binding is accepted and left byte-identical.
+ await fs.writeFile(marker,JSON.stringify(base));
+ const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'test',selection:family,runtimeBuild:origin});
+ await bindRuntimePrefix(context);
+ expect(await fs.readFile(marker,'utf8')).toBe(JSON.stringify(base));
+ expect(await fs.readFile(path.join(legacy.compatibilityDataPath,'save'),'utf8')).toBe('legacy build progress');
+});
+it('validates a recorded contract shape without pretending a default Wine runner verified it',async()=>{
+ await fixture();const origin=await approval(),legacy=await legacyBuildPrefix('test',origin);
+ const marker=path.join(legacy.compatibilityDataPath,'.nexus-runtime-family.json');
+ const base=JSON.parse(await fs.readFile(marker,'utf8'));
+ const context=()=>resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'test',selection:'default',runtimeBuild:origin});
+ // A default runner keeps the recorded contract untouched and does not rewrite it.
+ await bindRuntimePrefix(await context());
+ expect(await fs.readFile(marker,'utf8')).toBe(JSON.stringify(base));
+ // An unknown but well-formed contract is preserved as-is for a default runner.
+ const future={...base,prefixSchema:2,arch:'arm64'};await fs.writeFile(marker,JSON.stringify(future));
+ await bindRuntimePrefix(await context());
+ expect(await fs.readFile(marker,'utf8')).toBe(JSON.stringify(future));
+ // A managed runner compares the recorded contract exactly.
+ const managed=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'test',selection:family,runtimeBuild:origin});
+ await expect(bindRuntimePrefix(managed)).rejects.toThrow('mismatch');
});
it('rejects prefix symlinks and never writes into their target',async()=>{
- await fixture();const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:'test',selection:family,separatePrefix:true,approvedBuild:await approval(),defaultWine:'/default/wine',arch:'x64'});
+ await fixture();
+ const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'test',selection:family});
const other=path.join(root,'untouched');await fs.mkdir(other);await fs.mkdir(path.dirname(context.compatibilityDataPath),{recursive:true});await fs.symlink(other,context.compatibilityDataPath);
await expect(bindRuntimePrefix(context)).rejects.toThrow('symlinks');expect(await fs.readdir(other)).toEqual([]);
});
-it('persists valid game selections and rejects malformed updates without changing existing state',async()=>{
+it('keeps experimental prefix protection when the game switches to the default runner',async()=>{
+ await fixture();const origin=await approval(),legacy=await legacyBuildPrefix('test',origin);
+ const marker=path.join(legacy.compatibilityDataPath,'.nexus-runtime-family.json');
+ // A symlinked binding is rejected even though the current runner is the default Wine.
+ const real=path.join(root,'real-binding');await fs.writeFile(real,JSON.stringify({schema:1,family,buildId:origin.buildId,sourceCommit:origin.sourceCommit,manifestSha256:origin.manifestSha256,prefixSchema:1,arch:'x64'}));
+ await fs.unlink(marker);await fs.symlink(real,marker);
+ const symlinkedMarker=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'test',selection:'default',runtimeBuild:origin});
+ expect(symlinkedMarker.compatibilityDataPath).toBe(legacy.compatibilityDataPath);
+ await expect(bindRuntimePrefix(symlinkedMarker)).rejects.toThrow('regular file');
+ expect(await fs.readFile(real,'utf8')).toContain(origin.buildId);
+ // A symlinked prefix directory is rejected as well, with its target untouched.
+ await fs.unlink(marker);await fs.writeFile(marker,await fs.readFile(real,'utf8'));
+ const moved=path.join(root,'moved-prefix');await fs.rename(legacy.compatibilityDataPath,moved);await fs.symlink(moved,legacy.compatibilityDataPath);
+ const symlinkedPrefix=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'test',selection:'default',runtimeBuild:origin});
+ await expect(bindRuntimePrefix(symlinkedPrefix)).rejects.toThrow('symlinks');
+ expect(await fs.readFile(path.join(moved,'save'),'utf8')).toBe('legacy build progress');
+});
+it('persists valid game selections and rejects malformed identities without changing existing state',async()=>{
const {StateStore}=await import('./store');const store=new StateStore(path.join(root,'profile'));
await store.upsertGame({id:'test',path:'/synthetic/game',title:'Synthetic',installState:'ready',addedAt:'2026-01-01'});
- await store.patchGame('test',{runtime:family,runtimeSeparatePrefix:true});
+ await store.patchGame('test',{runtime:family,runtimePrefixIdentity:{layout:'game'}});
const reloaded=new StateStore(path.join(root,'profile'));await reloaded.load();
- expect(reloaded.games[0]).toMatchObject({runtime:family,runtimeSeparatePrefix:true});
+ expect(reloaded.games[0]).toMatchObject({runtime:family,runtimePrefixIdentity:{layout:'game'}});
await expect(store.patchGame('test',{runtime:'/bin/wine' as never})).rejects.toThrow('Unknown');
await expect(store.patchGame('test',{runtimeSeparatePrefix:'yes' as never})).rejects.toThrow('Invalid');
+ for(const forged of [{layout:'build',family:'../escape'},{layout:'build',family:'nexus',origin:{}},{layout:'/tmp/prefix'}])
+ await expect(store.patchGame('test',{runtimePrefixIdentity:forged as never})).rejects.toThrow();
+ expect(store.games[0].runtimePrefixIdentity).toEqual({layout:'game'});
expect(store.games[0].runtime).toBe(family);
});
+it('rejects a malformed persisted identity and ignores renderer-supplied prefix paths',async()=>{
+ await fixture();
+ const options={runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'test',selection:family};
+ for(const forged of [{layout:'build',family:'../escape'},{layout:'family',family:'/bin/sh'},{layout:'/tmp/prefix'},'../prefix'])
+ await expect(resolveGameRuntime({...options,runtimePrefixIdentity:forged})).rejects.toThrow('Invalid runtime prefix identity');
+ // An injected path is not part of the identity model and cannot redirect the prefix.
+ const injected=path.join(root,'renderer-prefix');
+ const context=await resolveGameRuntime({...options,runtimePrefixIdentity:{layout:'game',path:injected}});
+ expect(context.compatibilityDataPath).toBe(path.join(root,'compatdata','test'));
+ await bindRuntimePrefix(context);
+ expect(await present(injected)).toBe(false);
+ expect(runtimePrefixIdentity({layout:'game',path:injected})).toEqual({layout:'game'});
+});
+it('rejects a hostile persisted game id before any prefix path is derived',async()=>{
+ await fixture();
+ await expect(captureGamePrefixIdentity({dataRoot:root,gameId:'../escape',game:{runtime:family}})).rejects.toThrow('Invalid game prefix identity');
+ await expect(resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',gameId:'../escape',selection:family})).rejects.toThrow('Invalid game prefix identity');
+ await expect(present(path.join(path.dirname(root),'escape'))).resolves.toBe(false);
+});
+it('adopts the single existing historical prefix and keeps it stable across default, CachyOS and Standard',async()=>{
+ await fixture();const standardRelease=await secondFamily('nexus');
+ const cached=await legacyFamilyPrefix('test',family);
+ const save=path.join(cached.compatibilityDataPath,'save'),originalBytes=await digest(save);
+ // Current selection is default and has no prefix of its own: the one known
+ // historical prefix is adopted without guessing, copying or merging.
+ let game={...savedGame(),runtime:'default'} as Game;
+ expect(await captureGamePrefixIdentity({dataRoot:root,gameId:'test',game:game})).toEqual({layout:'family',family});
+ const context=async()=>resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(game)});
+ Object.assign(game,await approve(game,{runtime:'default'}));
+ expect(game.runtimePrefixIdentity).toEqual({layout:'family',family});
+ for(const choice of ['default',family,'nexus'] as const) {
+ Object.assign(game,await approve(game,{runtime:choice}));
+ const current=await context();await bindRuntimePrefix(current);
+ expect(current.compatibilityDataPath).toBe(cached.compatibilityDataPath);
+ expect(await digest(save)).toBe(originalBytes);
+ expect(current.winePath).toBe(choice==='default'?'/default/wine':choice==='nexus'?standardRelease:path.join(release,'files/bin/wine'));
+ }
+ expect(await present(path.join(root,'compatdata'))).toBe(false);
+});
+it('fails closed on several existing prefixes that the current selection does not use, preserving every byte',async()=>{
+ await fixture();await secondFamily('nexus');
+ const cached=await legacyFamilyPrefix('test',family),standard=await legacyFamilyPrefix('test','nexus');
+ const cachedBytes=await digest(path.join(cached.compatibilityDataPath,'save')),standardBytes=await digest(path.join(standard.compatibilityDataPath,'save'));
+ const markerBytes=await fs.readFile(path.join(cached.compatibilityDataPath,'.nexus-runtime-family.json'),'utf8');
+ const game={...savedGame(),runtime:'default',runtimePrefixes:{[family]:{layout:'family'},nexus:{layout:'family'}}} as Game;
+ await expect(captureGamePrefixIdentity({dataRoot:root,gameId:'test',game})).rejects.toThrow('several existing runtime prefixes');
+ await expect(resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(game)})).rejects.toThrow('several existing runtime prefixes');
+ await expect(approve(game,{runtime:'default'})).rejects.toThrow('several existing runtime prefixes');
+ // A launch, a settings save and readiness all refuse before anything is written.
+ expect(await gameRuntimeReadiness(()=>({game,runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64'}))).toBe(false);
+ expect(await digest(path.join(cached.compatibilityDataPath,'save'))).toBe(cachedBytes);
+ expect(await digest(path.join(standard.compatibilityDataPath,'save'))).toBe(standardBytes);
+ expect(await fs.readFile(path.join(cached.compatibilityDataPath,'.nexus-runtime-family.json'),'utf8')).toBe(markerBytes);
+ expect(await present(path.join(root,'compatdata'))).toBe(false);
+ // The capture rule itself is unchanged: a persisted record whose own selection
+ // owns an existing prefix resolves that prefix. Recovering such a legacy
+ // ambiguity needs deliberate prefix recovery, not the family selector, because
+ // capture runs on the current record before a new choice is persisted.
+ const owned={...game,runtime:family};
+ expect(await captureGamePrefixIdentity({dataRoot:root,gameId:'test',game:owned})).toEqual({layout:'family',family});
+ expect((await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(owned)})).compatibilityDataPath).toBe(cached.compatibilityDataPath);
+ expect(await fs.readFile(path.join(standard.compatibilityDataPath,'save'),'utf8')).toBe('nexus progress');
+});
+it('keeps the unbound experimental prefix rejection when the default runner is selected',async()=>{
+ await fixture();const legacy=await legacyFamilyPrefix('test',family);
+ const marker=path.join(legacy.compatibilityDataPath,'.nexus-runtime-family.json');
+ const saveBytes=await digest(path.join(legacy.compatibilityDataPath,'save'));
+ await fs.unlink(marker);
+ // The persisted identity keeps the exact experimental location; the runner is
+ // the default Wine one, which must not bypass the unknown-provenance check.
+ const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'test',selection:'default',runtimePrefixIdentity:{layout:'family',family}});
+ expect(context.compatibilityDataPath).toBe(legacy.compatibilityDataPath);
+ expect(context.managed).toBeUndefined();
+ await expect(bindRuntimePrefix(context)).rejects.toThrow('no runtime binding');
+ expect(await fs.readFile(path.join(legacy.compatibilityDataPath,'save'),'utf8')).toBe(`${family} progress`);
+ expect(await digest(path.join(legacy.compatibilityDataPath,'save'))).toBe(saveBytes);
+ expect(await present(marker)).toBe(false);
+ // An empty experimental prefix stays unbound and no marker is invented.
+ const empty=path.join(root,'runtime-prefixes',family,'prefixes','empty','compatdata');
+ const emptyContext=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'empty',selection:'default',runtimePrefixIdentity:{layout:'family',family}});
+ await bindRuntimePrefix(emptyContext);
+ expect(await present(empty)).toBe(false);
+ // A genuinely bound prefix still works with the default runner, marker untouched.
+ const bound=await legacyFamilyPrefix('bound');
+ const boundMarker=path.join(bound.compatibilityDataPath,'.nexus-runtime-family.json');
+ const boundBytes=await fs.readFile(boundMarker,'utf8');
+ const boundContext=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'bound',selection:'default',runtimePrefixIdentity:{layout:'family',family}});
+ await bindRuntimePrefix(boundContext);
+ expect(await fs.readFile(boundMarker,'utf8')).toBe(boundBytes);
+ expect(await fs.readFile(path.join(bound.compatibilityDataPath,'save'),'utf8')).toBe(`${family} progress`);
+});
+it('never adopts a historical prefix whose binding describes another location',async()=>{
+ await fixture();const origin=await approval();
+ // A build binding inside the family-wide directory must not be adopted as a build prefix.
+ const misplaced=path.join(root,'runtime-prefixes',family,'prefixes','test','compatdata');
+ await fs.mkdir(misplaced,{recursive:true});
+ await fs.writeFile(path.join(misplaced,'.nexus-runtime-family.json'),JSON.stringify({schema:1,family,buildId:origin.buildId,sourceCommit:origin.sourceCommit,manifestSha256:origin.manifestSha256,prefixSchema:1,arch:'x64'}));
+ await fs.writeFile(path.join(misplaced,'save'),'misplaced progress');
+ await expect(captureGamePrefixIdentity({dataRoot:root,gameId:'test',game:{runtime:'default'}})).rejects.toThrow('no verifiable binding');
+ // A build directory whose binding names a different build is refused as well.
+ const mismatchBuild='e'.repeat(64),directory=path.join(root,'runtime-prefixes',family,mismatchBuild,'other','compatdata');
+ await fs.mkdir(directory,{recursive:true});
+ await fs.writeFile(path.join(directory,'.nexus-runtime-family.json'),JSON.stringify({schema:1,family,buildId:origin.buildId,sourceCommit:origin.sourceCommit,manifestSha256:origin.manifestSha256,prefixSchema:1,arch:'x64'}));
+ await fs.writeFile(path.join(directory,'save'),'other progress');
+ await expect(captureGamePrefixIdentity({dataRoot:root,gameId:'other',game:{runtime:'default'}})).rejects.toThrow('no verifiable binding');
+ // Both locations and their bytes stay untouched.
+ expect(await fs.readFile(path.join(misplaced,'save'),'utf8')).toBe('misplaced progress');
+ expect(await fs.readFile(path.join(directory,'save'),'utf8')).toBe('other progress');
+});
+it('prefers the canonical prefix when a legacy family directory holds no prefix',async()=>{
+ await fixture();const empty=path.join(root,'runtime-prefixes',family,'prefixes','test');await fs.mkdir(empty,{recursive:true});
+ expect(await captureGamePrefixIdentity({dataRoot:root,gameId:'test',game:{runtime:family,runtimePrefixes:{[family]:{layout:'family'}}}})).toEqual({layout:'game'});
+ expect(await fs.readdir(empty)).toEqual([]);
+});
+it('adopts a prefix that exists only as the legacy plain Wine root',async()=>{
+ await fixture();
+ await fs.mkdir(path.join(root,'prefixes','test'),{recursive:true});
+ await fs.writeFile(path.join(root,'prefixes','test','save'),'plain wine progress');
+ const game=savedGame();
+ const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(game)});
+ expect(context.identity).toEqual({layout:'game'});
+ expect(context.compatibilityDataPath).toBe(path.join(root,'compatdata','test'));
+ expect(context.legacyPrefixRoot).toBe(path.join(root,'prefixes','test'));
+ await bindRuntimePrefix(context);
+ expect(await fs.readFile(path.join(root,'prefixes','test','save'),'utf8')).toBe('plain wine progress');
+});
+it('ignores unknown entries in the experimental prefix tree instead of adopting them',async()=>{
+ await fixture();
+ const arbitrary=path.join(root,'runtime-prefixes',family,'renderer-forged','test');
+ await fs.mkdir(path.join(arbitrary,'compatdata'),{recursive:true});
+ await fs.writeFile(path.join(arbitrary,'compatdata','save'),'unrelated');
+ await fs.writeFile(path.join(arbitrary,'compatdata','.nexus-runtime-family.json'),JSON.stringify({schema:2,layout:'family',family,prefixSchema:1,arch:'x64'}));
+ expect(await captureGamePrefixIdentity({dataRoot:root,gameId:'test',game:{runtime:'default'}})).toEqual({layout:'game'});
+ expect(await fs.readFile(path.join(arbitrary,'compatdata','save'),'utf8')).toBe('unrelated');
+});
+it('accepts an unrecorded prefix contract but rejects a partial or invalid one',async()=>{
+ await fixture();
+ const canonical=path.join(root,'compatdata','test'),marker=path.join(canonical,'.nexus-runtime-family.json');
+ await fs.mkdir(canonical,{recursive:true});await fs.writeFile(path.join(canonical,'save'),'progress');
+ const context=()=>resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'test',selection:family});
+ for(const forged of [{schema:3,layout:'game',gameId:'test',prefixSchema:1},{schema:3,layout:'game',gameId:'test',arch:'x64'},{schema:3,layout:'game',gameId:'test',prefixSchema:'1',arch:'x64'},{schema:3,layout:'game',gameId:'test',prefixSchema:1,arch:7},{schema:3,layout:'game',gameId:'other',prefixSchema:1,arch:'x64'}]) {
+ await fs.writeFile(marker,JSON.stringify(forged));
+ await expect(bindRuntimePrefix(await context())).rejects.toThrow('mismatch');
+ }
+ // A prefix created without a managed payload records no contract and stays usable.
+ const unrecorded=JSON.stringify({schema:3,layout:'game',gameId:'test'});
+ await fs.writeFile(marker,unrecorded);
+ const managed=await context();await bindRuntimePrefix(managed);
+ expect(await fs.readFile(marker,'utf8')).toBe(unrecorded);
+ expect(await fs.readFile(path.join(canonical,'save'),'utf8')).toBe('progress');
+});
+it('does not gate a family choice on separate-prefix consent',()=>{
+ const installed={id:family,label:'CachyOS',buildId,sourceCommit,manifestSha256:hash('x')};
+ expect(gameRuntimeAvailable(family,false,[installed])).toBe(true);
+ expect(gameRuntimeAvailable(family,true,[])).toBe(false);
+ expect(gameRuntimeAvailable('default',false,[])).toBe(false);
+ expect(gameRuntimeAvailable(undefined,true,[installed])).toBe(true);
+});
it('Stop uses its captured runtime and prefix after another launch is selected',async()=>{
await fixture();
@@ -108,17 +448,17 @@ it('Stop uses its captured runtime and prefix after another launch is selected',
const manifest=JSON.parse(await fs.readFile(manifestFile,'utf8'));manifest.files['files/bin/wineserver']=hash(await fs.readFile(server));
const bytes=JSON.stringify(manifest);await fs.writeFile(manifestFile,bytes);
const pointer=JSON.parse(await fs.readFile(pointerFile,'utf8'));pointer.manifestSha256=hash(bytes);await fs.writeFile(pointerFile,JSON.stringify(pointer));
- const options={runtimeRoot:root,dataRoot:root,gameId:'test',defaultWine:'/default/wine',arch:'x64',approvedBuild:await approval()};
- const captured=await resolveGameRuntime({...options,selection:family,separatePrefix:true});await bindRuntimePrefix(captured);
+ const options={runtimeRoot:root,dataRoot:root,gameId:'test',defaultWine:'/default/wine',arch:'x64'};
+ const captured=await resolveGameRuntime({...options,selection:family});await bindRuntimePrefix(captured);
const system32=path.join(captured.compatibilityDataPath,'pfx/drive_c/windows/system32');await fs.mkdir(system32,{recursive:true});
for(const name of ['libvkd3d-utils-1.dll','dxgi.dll','d3d12.dll'])await fs.writeFile(path.join(system32,name),'synthetic');
const runner=await prepareProtonRunner(captured.winePath,captured.compatibilityDataPath,path.join(root,'synthetic-steam'));
expect(runner).toBeDefined();
- await resolveGameRuntime({...options,selection:'default',separatePrefix:false});
+ await resolveGameRuntime({...options,selection:'default'});
await fs.unlink(pointerFile); // Current selection/pointer cannot change a running Stop command.
await promisify(execFileCallback)(runner!.stopPrefix.command,runner!.stopPrefix.args);
expect((await fs.readFile(stopLog,'utf8')).trim()).toBe(path.join(captured.compatibilityDataPath,'pfx'));
- expect(await fs.readdir(path.join(root,'compatdata')).catch(()=>[])).toEqual([]);
+ expect(await fs.readdir(path.join(root,'compatdata'))).toEqual(['test']);
});
it.each([{sourceRepository:'xodus-gaming/Proton'},{sourceCommit:'bad'},{family:'nexus'},{buildId:'../escape'},{manifestSha256:'0'.repeat(64)}])('rejects a mismatched or hostile installed receipt: %j',async patch=>{
@@ -189,8 +529,8 @@ it('rejects a same-bytes write during full verification and does not cache the r
it('rejects a default-runtime alias into a managed family but preserves ordinary default symlinks',async()=>{
await fixture();const alias=path.join(root,'wine-alias');await fs.symlink(path.join(release,'files/bin/wine'),alias);
- const options={runtimeRoot:root,dataRoot:root,gameId:'test',selection:'default',separatePrefix:false,arch:'x64'};
- await expect(resolveGameRuntime({...options,defaultWine:alias})).rejects.toThrow('separate prefix');
+ const options={runtimeRoot:root,dataRoot:root,gameId:'test',selection:'default',arch:'x64'};
+ await expect(resolveGameRuntime({...options,defaultWine:alias})).rejects.toThrow('cannot be the default Wine');
await fs.unlink(alias);const legacy=path.join(root,'legacy-wine');await fs.writeFile(legacy,'synthetic');await fs.symlink(legacy,alias);
expect((await resolveGameRuntime({...options,defaultWine:alias})).winePath).toBe(alias);
});
@@ -218,40 +558,33 @@ async function switchBuild(id:string) {
return {buildId:id,sourceCommit,manifestSha256:hash(bytes)};
}
const savedGame=():Game=>({id:'test',path:'/synthetic/game',title:'Synthetic',installState:'ready',addedAt:'2026-01-01'});
-it('follows verified current B with the same new-family prefix and existing saves, while captured A remains immutable',async()=>{
- await fixture();let game=savedGame();Object.assign(game,await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true},root));
- const options=()=>({runtimeRoot:root,dataRoot:root,gameId:game.id,selection:game.runtime,separatePrefix:game.runtimeSeparatePrefix,prefixAnchor:game.runtimePrefixes?.[family],defaultWine:'/default/wine',arch:'x64'});
+let paths:RuntimeSettingsPaths;
+const approve=(game:Game,request:RuntimeSettingsRequest,resolve=resolveRuntimeFamily)=>approvedRuntimeSettings(game,request,paths,resolve);
+it('follows verified current B with the same per-game prefix and existing saves, while captured A remains immutable',async()=>{
+ await fixture();let game=savedGame();Object.assign(game,await approve(game,{runtime:family}));
+ const options=()=>({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(game)});
const a=await resolveGameRuntime(options());await bindRuntimePrefix(a);const save=path.join(a.compatibilityDataPath,'save');await fs.writeFile(save,'real synthetic progress');const ino=(await fs.stat(save)).ino;
await retainRuntimeFamilyBuild(root,family,'x64');await switchBuild('d'.repeat(64));
const b=await resolveGameRuntime(options());await bindRuntimePrefix(b);expect(b.winePath).not.toBe(a.winePath);expect(b.compatibilityDataPath).toBe(a.compatibilityDataPath);expect(a.managed?.buildId).toBe(buildId);expect(b.managed?.buildId).toBe('d'.repeat(64));
expect(await fs.readFile(save,'utf8')).toBe('real synthetic progress');expect((await fs.stat(save)).ino).toBe(ino);
const noResolve=vi.fn(()=>{throw Error('Ordinary Save must not need a new build approval');});
- expect((await approvedRuntimeSettings(game,{},root,noResolve)).runtimePrefixes).toEqual(game.runtimePrefixes);expect(noResolve).not.toHaveBeenCalled();
-});
-it('preserves old build-specific prefix origin across default and back without moving or resetting progress',async()=>{
- await fixture();const origin=await approval();let game={...savedGame(),runtime:family,runtimeSeparatePrefix:true,runtimeBuild:origin} as Game;
- const old=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:game.id,selection:family,separatePrefix:true,approvedBuild:origin,defaultWine:'/default/wine',arch:'x64'});await bindRuntimePrefix(old);
- const save=path.join(old.compatibilityDataPath,'save');await fs.writeFile(save,'old progress');const marker=await fs.readFile(path.join(old.compatibilityDataPath,'.nexus-runtime-family.json'),'utf8');
- Object.assign(game,await approvedRuntimeSettings(game,{runtime:'default'},root));expect(game.runtimeBuild).toBeUndefined();expect(game.runtimePrefixes?.[family]).toEqual({layout:'build',origin});
- await switchBuild('d'.repeat(64));Object.assign(game,await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true},root));
- const next=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:game.id,selection:family,separatePrefix:true,prefixAnchor:game.runtimePrefixes?.[family],defaultWine:'/default/wine',arch:'x64'});await bindRuntimePrefix(next);
- expect(next.compatibilityDataPath).toBe(old.compatibilityDataPath);expect(next.winePath).not.toBe(old.winePath);expect(await fs.readFile(save,'utf8')).toBe('old progress');expect(await fs.readFile(path.join(next.compatibilityDataPath,'.nexus-runtime-family.json'),'utf8')).toBe(marker);
- const {StateStore}=await import('./store');const store=new StateStore(path.join(root,'profile'));await store.upsertGame(game);await store.patchGame(game.id,{title:'Renamed'});const loaded=new StateStore(path.join(root,'profile'));await loaded.load();expect(loaded.games[0].runtimePrefixes).toEqual(game.runtimePrefixes);
-});
-it('requires first family consent, accepts updates without fresh consent, and ignores renderer-forged prefix identities',async()=>{
- await fixture();const game=savedGame();await expect(approvedRuntimeSettings(game,{runtime:family},root)).rejects.toThrow('separate prefix');
- const patch=await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true,runtimePrefixes:{[family]:{layout:'build',origin:await approval()}}} as never,root);
- expect(patch.runtimePrefixes).toEqual({[family]:{layout:'family'}});expect(patch.runtimeBuild).toBeUndefined();
- Object.assign(game,patch);await switchBuild('d'.repeat(64));expect((await approvedRuntimeSettings(game,{},root)).runtimePrefixes).toEqual(game.runtimePrefixes);
- await expect(fs.stat(path.join(root,'runtime-prefixes'))).rejects.toMatchObject({code:'ENOENT'});
-});
-it('same-family ordinary Save preserves compatibility origin even when current runtime is unavailable',async()=>{
- await fixture();const origin=await approval(),game={...savedGame(),runtime:family,runtimeSeparatePrefix:true,runtimeBuild:origin} as Game;
- await fs.unlink(path.join(root,'variants',family,'current.json'));
- const patch=await approvedRuntimeSettings(game,{},root);expect(patch.runtimePrefixes).toEqual({[family]:{layout:'build',origin}});
- await expect(resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:game.id,selection:family,separatePrefix:true,prefixAnchor:patch.runtimePrefixes?.[family],defaultWine:'/default/wine',arch:'x64'})).rejects.toThrow();
+ const patch=await approve(game,{},noResolve);
+ expect(patch.runtimePrefixIdentity).toEqual(game.runtimePrefixIdentity);expect(noResolve).not.toHaveBeenCalled();
+});
+it('retains A for rollback but next launch follows B with the same preserved prefix',async()=>{
+ await fixture();const a=await approval();await legacyBuildPrefix('retained',a);
+ const game={...savedGame(),id:'retained',runtime:family,runtimeBuild:a} as Game;
+ const options={runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(game)};
+ const old=await resolveGameRuntime(options);await bindRuntimePrefix(old);
+ expect(old.compatibilityDataPath).toBe(path.join(root,'runtime-prefixes',family,a.buildId,'retained','compatdata'));
+ await fs.writeFile(path.join(old.compatibilityDataPath,'save'),'A progress');
+ await retainRuntimeFamilyBuild(root,family,'x64');await installNextFixture();
+ const next=await resolveGameRuntime(options);await bindRuntimePrefix(next);
+ expect(next.winePath).not.toBe(old.winePath);expect(next.compatibilityDataPath).toBe(old.compatibilityDataPath);expect(await fs.readFile(path.join(next.compatibilityDataPath,'save'),'utf8')).toBe('A progress');
+ expect((await resolveRuntimeFamilyBuild(root,family,a,'x64')).winePath).toBe(old.winePath);
+ await fs.writeFile(path.join(root,'variants',family,'current.json'),JSON.stringify({schema:1,family,sourceRepository,...a}));
+ expect((await resolveGameRuntime(options)).winePath).toBe(old.winePath);
});
-
async function installNextFixture() {
const previous=release;
const next='d'.repeat(64);release=path.join(root,'variants',family,'releases',next);
@@ -264,14 +597,6 @@ async function installNextFixture() {
await fs.writeFile(path.join(root,'variants',family,'current.json'),JSON.stringify(pointer));
return previous;
}
-it('retains A for rollback but next launch follows B with the same compatibility prefix',async()=>{
- await fixture();const a=await approval();const options={runtimeRoot:root,dataRoot:root,gameId:'retained',selection:family,separatePrefix:true,defaultWine:'/default/wine',arch:'x64',approvedBuild:a};
- const old=await resolveGameRuntime(options);await bindRuntimePrefix(old);await fs.writeFile(path.join(old.compatibilityDataPath,'save'),'A progress');await retainRuntimeFamilyBuild(root,family,'x64');await installNextFixture();
- const next=await resolveGameRuntime(options);await bindRuntimePrefix(next);expect(next.winePath).not.toBe(old.winePath);expect(next.compatibilityDataPath).toBe(old.compatibilityDataPath);expect(await fs.readFile(path.join(next.compatibilityDataPath,'save'),'utf8')).toBe('A progress');
- expect((await resolveRuntimeFamilyBuild(root,family,a,'x64')).winePath).toBe(old.winePath);
- await fs.writeFile(path.join(root,'variants',family,'current.json'),JSON.stringify({schema:1,family,sourceRepository,...a}));
- expect((await resolveGameRuntime(options)).winePath).toBe(old.winePath);
-});
it('does not reconstruct missing A receipts from an approved identity or an existing release directory',async()=>{
await fixture();const a=await approval();await installNextFixture();
await expect(resolveRuntimeFamilyBuild(root,family,a,'x64')).rejects.toThrow();
@@ -346,24 +671,93 @@ it('reports unavailable for missing or corrupt current B despite retaining A for
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=>{
+it.each(['approval','runtimeRoot','identity'])('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';
+ if(changed==='approval')state.game={...state.game!,runtimeBuild:{...state.game!.runtimeBuild!,buildId:'d'.repeat(64)}};
+ else if(changed==='identity')state.game={...state.game!,runtimePrefixIdentity:{layout:'game'}};
+ else state.runtimeRoot+='-changed';
resume();expect(await result).toBe(false);
});
-
-it('preserves independent family anchors and saves through family1 to family2 to family1',async()=>{
- await fixture();const second='nexus';const secondRoot=path.join(root,'variants',second);await fs.cp(path.join(root,'variants',family),secondRoot,{recursive:true});
- const manifestFile=path.join(secondRoot,'releases',buildId,'nexus-family.json');const manifest=JSON.parse(await fs.readFile(manifestFile,'utf8'));manifest.family=second;manifest.sourceRepository='domsvoboda/nexus-runtime';const bytes=JSON.stringify(manifest);await fs.writeFile(manifestFile,bytes);await fs.writeFile(path.join(secondRoot,'current.json'),JSON.stringify({schema:1,family:second,buildId,sourceRepository:manifest.sourceRepository,sourceCommit,manifestSha256:hash(bytes)}));
- let game=savedGame();const context=()=>resolveGameRuntime({runtimeRoot:root,dataRoot:root,gameId:game.id,selection:game.runtime,separatePrefix:game.runtimeSeparatePrefix,prefixAnchor:game.runtimePrefixes?.[game.runtime as typeof family],defaultWine:'/default/wine',arch:'x64'});
- Object.assign(game,await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true},root));const first=await context();await bindRuntimePrefix(first);await fs.writeFile(path.join(first.compatibilityDataPath,'save'),'family1');
- await expect(approvedRuntimeSettings(game,{runtime:second},root)).rejects.toThrow('Explicit separate prefix');
- Object.assign(game,await approvedRuntimeSettings(game,{runtime:second,runtimeSeparatePrefix:true},root));const other=await context();await bindRuntimePrefix(other);await fs.writeFile(path.join(other.compatibilityDataPath,'save'),'family2');
- Object.assign(game,await approvedRuntimeSettings(game,{runtime:family,runtimeSeparatePrefix:true},root));expect((await context()).compatibilityDataPath).toBe(first.compatibilityDataPath);expect(Object.keys(game.runtimePrefixes!)).toHaveLength(2);expect(await fs.readFile(path.join(first.compatibilityDataPath,'save'),'utf8')).toBe('family1');expect(await fs.readFile(path.join(other.compatibilityDataPath,'save'),'utf8')).toBe('family2');
+it('readiness and launch resolve the same per-game prefix for the same persisted record',async()=>{
+ await fixture();const legacy=await legacyBuildPrefix('readiness',await approval());
+ const game={...savedGame(),id:'readiness',runtime:family} as Game;
+ expect(await gameRuntimeReadiness(()=>({game,runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64'}))).toBe(true);
+ const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(game)});
+ // Both entry points adopt the single existing historical prefix, never a new one.
+ expect(context.compatibilityDataPath).toBe(legacy.compatibilityDataPath);
+});
+it('holds the activity reservation from before the async verification through the persisted write',async()=>{
+ await fixture();const game=savedGame();
+ let held=false,launchAttempts=0;
+ const reserve=()=>{
+ expect(held).toBe(false);held=true;
+ return {
+ admit:()=>{expect(held).toBe(true);},
+ release:()=>{expect(held).toBe(true);held=false;},
+ };
+ };
+ // A launch or component update entry point fails while the reservation is held.
+ const enterLaunch=()=>{launchAttempts++;if(held)throw Error('Component updates are in progress.');};
+ const persist=vi.fn(async(patch:Partial<Game>)=>{expect(held).toBe(true);return {...game,...patch};});
+ let resume!:()=>void;const pending=new Promise<void>(resolve=>{resume=resolve;});
+ const approve=vi.fn(async()=>{await pending;expect(held).toBe(true);enterLaunch;return {runtime:family,runtimePrefixIdentity:{layout:'game'} as const};});
+ const running=guardedRuntimeSettings({current:game,request:{runtime:family},paths,changing:true,reserve,read:()=>game,persist,approve});
+ await Promise.resolve();
+ // The reservation is already held while the verification is still pending.
+ expect(held).toBe(true);expect(()=>enterLaunch()).toThrow('Component updates are in progress.');
+ resume();
+ const saved=await running;
+ expect(saved.runtime).toBe(family);expect(persist).toHaveBeenCalledTimes(1);
+ expect(held).toBe(false);expect(launchAttempts).toBe(1);
+});
+it('releases the reservation when verification or the persisted record check fails',async()=>{
+ await fixture();const game=savedGame();
+ let held=false;
+ const reserve=()=>({admit:()=>{},release:()=>{held=false;}});
+ held=true;
+ await expect(guardedRuntimeSettings({current:game,request:{runtime:family},paths,changing:true,reserve,read:()=>({...game,runtime:'default',runtimePrefixIdentity:{layout:'game'}}),persist:async()=>game,approve:async()=>({runtime:family})})).rejects.toThrow('changed');
+ expect(held).toBe(false);
+ held=true;
+ await expect(guardedRuntimeSettings({current:game,request:{runtime:family},paths,changing:true,reserve,read:()=>game,persist:async()=>game,approve:async()=>{throw Error('default was not used');}})).rejects.toThrow('default was not used');
+ expect(held).toBe(false);
+ // A reservation that cannot be acquired blocks the change before any write.
+ await expect(guardedRuntimeSettings({current:game,request:{runtime:family},paths,changing:true,reserve:()=>{throw Error('Another Xodus operation is active. Wait for it to finish or stop it first.');},read:()=>game,persist:async()=>game,approve:async()=>({runtime:family})})).rejects.toThrow('operation is active');
+});
+it('does not reserve activity for an unchanged runtime but still refuses a changed record',async()=>{
+ await fixture();const game=savedGame();
+ let reserved=0;
+ const reserve=()=>{reserved++;return {admit:()=>{},release:()=>{}};};
+ const saved=await guardedRuntimeSettings({current:game,request:{runtime:'default'},paths,changing:false,reserve,read:()=>game,persist:async(patch)=>({...game,...patch}),approve:async()=>({runtime:'default',runtimePrefixIdentity:{layout:'game'}})});
+ expect(saved.runtimePrefixIdentity).toEqual({layout:'game'});
+ expect(reserved).toBe(0);
+ await expect(guardedRuntimeSettings({current:game,request:{runtime:'default'},paths,changing:false,reserve,read:()=>({...game,runtimePrefixIdentity:{layout:'family',family}}),persist:async()=>game,approve:async()=>({runtime:'default'})})).rejects.toThrow('changed');
+ expect(reserved).toBe(0);
+});
+it('persists the captured identity atomically with the selection and survives reload',async()=>{
+ await fixture();const {StateStore}=await import('./store');
+ const store=new StateStore(path.join(root,'profile'));
+ await store.upsertGame(savedGame());
+ const saved=await store.patchGame('test',await approve(store.games[0],{runtime:family}));
+ expect(saved.runtime).toBe(family);expect(saved.runtimePrefixIdentity).toEqual({layout:'game'});
+ const reloaded=new StateStore(path.join(root,'profile'));await reloaded.load();
+ const loaded=reloaded.games[0];
+ expect(loaded.runtimePrefixIdentity).toEqual({layout:'game'});
+ // The reloaded record resolves the same prefix even though the selection changed.
+ expect((await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(loaded)})).compatibilityDataPath).toBe(path.join(root,'compatdata','test'));
+ Object.assign(loaded,await approve(loaded,{runtime:'default'}));
+ expect((await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',...gameRuntimeParameters(loaded)})).compatibilityDataPath).toBe(path.join(root,'compatdata','test'));
});
it('rejects an old marker conflicting with its persisted origin without rewriting it or its save',async()=>{
- await fixture();const origin=await approval(),options={runtimeRoot:root,dataRoot:root,gameId:'old',selection:family,separatePrefix:true,approvedBuild:origin,defaultWine:'/default/wine',arch:'x64'};
- const a=await resolveGameRuntime(options);await bindRuntimePrefix(a);const marker=path.join(a.compatibilityDataPath,'.nexus-runtime-family.json');const invalid=JSON.stringify({...JSON.parse(await fs.readFile(marker,'utf8')),manifestSha256:'0'.repeat(64)});await fs.writeFile(marker,invalid);await fs.writeFile(path.join(a.compatibilityDataPath,'save'),'preserve');await switchBuild('d'.repeat(64));const b=await resolveGameRuntime(options);await expect(bindRuntimePrefix(b)).rejects.toThrow('mismatch');expect(await fs.readFile(marker,'utf8')).toBe(invalid);expect(await fs.readFile(path.join(a.compatibilityDataPath,'save'),'utf8')).toBe('preserve');
+ await fixture();const origin=await approval(),legacy=await legacyBuildPrefix('old',origin);
+ const marker=path.join(legacy.compatibilityDataPath,'.nexus-runtime-family.json');
+ const invalid=JSON.stringify({...JSON.parse(await fs.readFile(marker,'utf8')),manifestSha256:'0'.repeat(64)});
+ await fs.writeFile(marker,invalid);
+ await switchBuild('d'.repeat(64));
+ const context=await resolveGameRuntime({runtimeRoot:root,dataRoot:root,defaultWine:'/default/wine',arch:'x64',gameId:'old',selection:family,runtimeBuild:origin});
+ expect(context.compatibilityDataPath).toBe(legacy.compatibilityDataPath);
+ await expect(bindRuntimePrefix(context)).rejects.toThrow('mismatch');
+ expect(await fs.readFile(marker,'utf8')).toBe(invalid);
+ expect(await fs.readFile(path.join(legacy.compatibilityDataPath,'save'),'utf8')).toBe('legacy build progress');
});
diff --git a/src/main/runtime-prefix-binding.ts b/src/main/runtime-prefix-binding.ts
index a89f88d..8e0907e 100644
--- a/src/main/runtime-prefix-binding.ts
+++ b/src/main/runtime-prefix-binding.ts
@@ -1,38 +1,204 @@
import {promises as fs} from 'node:fs';
import path from 'node:path';
-import {gameRuntimeSelection,runtimePrefixAnchor,runtimeBuildApproval,type RuntimePrefixAnchor,type GameRuntimeSelection} from '../shared/runtime-selection.js';
+import {gameRuntimeSelection,legacyRuntimePrefixOrigin,runtimeFamilies,runtimePrefixIdentity,type GameRuntimeSelection,type RuntimeFamily,type RuntimePrefixIdentity} from '../shared/runtime-selection.js';
import {resolveRuntimeFamily,type ResolvedRuntimeFamily} from './runtime-families.js';
export interface GameRuntimeContext {
- readonly selection:GameRuntimeSelection;readonly family:'default'|'nexus'|'nexus-cachyos';
+ readonly selection:GameRuntimeSelection;
+ /** Durable prefix location captured before any selection change. */
+ readonly identity:Readonly<RuntimePrefixIdentity>;readonly gameId:string;
readonly winePath:string;readonly compatibilityDataPath:string;readonly legacyPrefixRoot:string;readonly dataRoot:string;
- readonly prefixAnchor?:Readonly<RuntimePrefixAnchor>;readonly managed?:Readonly<ResolvedRuntimeFamily>;
+ readonly managed?:Readonly<ResolvedRuntimeFamily>;
+}
+/** The persisted fields that may describe an existing game prefix. */
+export interface GameRuntimeParameters {
+ gameId:string;selection:unknown;runtimePrefixIdentity?:unknown;runtimeBuild?:unknown;runtimePrefixes?:unknown;
+}
+/** One mapping for launch, readiness and the settings entry point, so they can
+ * never resolve a different prefix for the same persisted game record. */
+export function gameRuntimeParameters(game:{id:string;runtime?:unknown;runtimePrefixIdentity?:unknown;runtimeBuild?:unknown;runtimePrefixes?:unknown}):GameRuntimeParameters {
+ return {gameId:game.id,selection:game.runtime,runtimePrefixIdentity:game.runtimePrefixIdentity,runtimeBuild:game.runtimeBuild,runtimePrefixes:game.runtimePrefixes};
+}
+export interface PrefixPaths {readonly compatibilityDataPath:string;readonly legacyPrefixRoot:string}
+/** Experimental layouts are only ever derived from a known family id plus the
+ * family-wide 'prefixes' directory or an exact 64 hex build id. */
+function experimentalPaths(dataRoot:string,gameId:string,family:RuntimeFamily,layout:'family'|'build',buildId?:string):PrefixPaths {
+ const root=path.join(dataRoot,'runtime-prefixes',family,layout==='build'?String(buildId):'prefixes',gameId);
+ return {compatibilityDataPath:path.join(root,'compatdata'),legacyPrefixRoot:path.join(root,'wine')};
+}
+/** Every derivation uses the same conservative id alphabet, so persisted or
+ * renderer-supplied text can never escape the prefix store. */
+function prefixGameId(value:string):string {
+ if(!/^[A-Za-z0-9_-]{1,128}$/.test(value))throw Error('Invalid game prefix identity.');
+ return value;
+}
+/** Backend-owned path derivation. Identity layouts select a fixed location; no
+ * renderer value can name a directory. */
+export function runtimePrefixPaths(dataRoot:string,gameId:string,identity:RuntimePrefixIdentity):PrefixPaths {
+ prefixGameId(gameId);
+ if(identity.layout==='game')return {compatibilityDataPath:path.join(dataRoot,'compatdata',gameId),legacyPrefixRoot:path.join(dataRoot,'prefixes',gameId)};
+ return identity.layout==='family'?experimentalPaths(dataRoot,gameId,identity.family,'family'):experimentalPaths(dataRoot,gameId,identity.family,'build',identity.origin.buildId);
+}
+async function prefixPresent(directory:string):Promise<boolean> {
+ let stat;
+ try { stat=await fs.lstat(directory); }
+ catch(error) { if((error as NodeJS.ErrnoException).code==='ENOENT')return false; throw error; }
+ // A symlink or an unexpected entry is still a prefix location; the binding
+ // step rejects it instead of silently choosing another directory.
+ if(stat.isSymbolicLink()||!stat.isDirectory())return true;
+ return (await fs.readdir(directory)).length>0;
+}
+/** A prefix may hold either a Proton compatdata tree or a plain Wine prefix. */
+async function prefixLocationPresent(paths:PrefixPaths):Promise<boolean> {
+ return await prefixPresent(paths.compatibilityDataPath)||await prefixPresent(paths.legacyPrefixRoot);
+}
+const markerName='.nexus-runtime-family.json';
+function plainObject(value:unknown):Record<string,unknown>|undefined {
+ if(!value||typeof value!=='object'||Array.isArray(value))return undefined;
+ const prototype=Object.getPrototypeOf(value) as unknown;
+ return prototype===Object.prototype||prototype===null?value as Record<string,unknown>:undefined;
+}
+/** Parsed binding file, or undefined only when no file exists. A file that
+ * parses to anything other than a plain object is returned as-is so validation
+ * rejects it instead of treating it as unbound. */
+async function readMarker(directory:string):Promise<unknown> {
+ let source:string;
+ try { source=await fs.readFile(path.join(directory,markerName),'utf8'); }
+ catch(error) { if((error as NodeJS.ErrnoException).code==='ENOENT')return undefined; throw error; }
+ try { return JSON.parse(source) as unknown; }
+ catch { throw Error('Runtime prefix binding is unreadable. Existing prefix was preserved.'); }
+}
+/** Origin of an existing experimental prefix, taken from its own binding. The
+ * binding must describe the layout that the directory name already implies, so
+ * an adopted identity can never point at another location. */
+async function boundExpectation(paths:PrefixPaths,family:RuntimeFamily,layout:'family'|'build',buildId?:string):Promise<RuntimePrefixIdentity|undefined> {
+ const marker=plainObject(await readMarker(paths.compatibilityDataPath));
+ if(!marker||marker.family!==family)return undefined;
+ if(layout==='family')return marker.schema===2&&marker.layout==='family'?{layout:'family',family}:undefined;
+ if(marker.schema!==1||marker.buildId!==buildId)return undefined;
+ try {
+ const identity=runtimePrefixIdentity({layout:'build',family,origin:{buildId:marker.buildId,sourceCommit:marker.sourceCommit,manifestSha256:marker.manifestSha256}});
+ return identity.layout==='build'?identity:undefined;
+ } catch { return undefined; }
+}
+interface PrefixCandidate extends PrefixPaths {readonly identity?:RuntimePrefixIdentity}
+/** Known historical locations of this game's prefix. Never invents entries from
+ * arbitrary directory names and never follows a path outside the prefix store. */
+async function historicalPrefixes(dataRoot:string,gameId:string):Promise<PrefixCandidate[]> {
+ const candidates:PrefixCandidate[]=[];
+ for(const family of runtimeFamilies) {
+ const directory=path.join(dataRoot,'runtime-prefixes',family);
+ let entries:string[];
+ try { entries=await fs.readdir(directory); }
+ catch(error) { if((error as NodeJS.ErrnoException).code==='ENOENT')continue; throw error; }
+ for(const entry of entries) {
+ if(entry!=='prefixes'&&!/^[a-f0-9]{64}$/.test(entry))continue;
+ const layout=entry==='prefixes'?'family':'build';
+ const paths=layout==='family'?experimentalPaths(dataRoot,gameId,family,'family'):experimentalPaths(dataRoot,gameId,family,'build',entry);
+ if(!await prefixLocationPresent(paths))continue;
+ candidates.push({...paths,identity:await boundExpectation(paths,family,layout,layout==='build'?entry:undefined)});
+ }
+ }
+ return candidates;
+}
+function multiplePrefixes():Error {
+ return Error('This game has several existing runtime prefixes. Existing prefix location is ambiguous; the runtime selection and all existing prefixes/saves were preserved.');
+}
+/**
+ * Resolve the durable prefix identity of a game.
+ *
+ * A persisted identity always wins. Otherwise the location that the persisted
+ * selection already uses is adopted, so existing prefixes and saves stay at their
+ * exact paths. When that location holds nothing, the single known historical
+ * prefix of this game is adopted (no guessing, no copying or merging). Several
+ * historical prefixes with none of them selected, or an experimental prefix
+ * without a usable binding, fail closed and preserve every byte.
+ */
+export async function captureGamePrefixIdentity(options:{dataRoot:string;gameId:string;game:Omit<GameRuntimeParameters,'gameId'|'selection'> & {runtime?:unknown}}):Promise<RuntimePrefixIdentity> {
+ prefixGameId(options.gameId);
+ if(options.game.runtimePrefixIdentity!==undefined)return runtimePrefixIdentity(options.game.runtimePrefixIdentity);
+ const state={runtime:options.game.runtime,runtimeBuild:options.game.runtimeBuild,runtimePrefixes:options.game.runtimePrefixes};
+ const origin=legacyRuntimePrefixOrigin(state);
+ if(await prefixLocationPresent(runtimePrefixPaths(options.dataRoot,options.gameId,origin)))return origin;
+ const canonicalPresent=origin.layout!=='game'&&await prefixLocationPresent(runtimePrefixPaths(options.dataRoot,options.gameId,{layout:'game'}));
+ const historical=await historicalPrefixes(options.dataRoot,options.gameId);
+ if(canonicalPresent) {
+ // The pre-0.5 per-game prefix exists but is not the current selection.
+ if(historical.length)throw multiplePrefixes();
+ return {layout:'game'};
+ }
+ if(!historical.length)return {layout:'game'};
+ if(historical.length>1)throw multiplePrefixes();
+ const identity=historical[0].identity;
+ if(!identity)throw Error('An existing runtime prefix has no verifiable binding. Existing prefixes and saves were preserved.');
+ return identity;
}
/** Capture once before prerequisite staging or launch. Later setting/pointer
* changes cannot redirect this session, its prefix or its captured Stop runner. */
-export async function resolveGameRuntime(options:{runtimeRoot:string;dataRoot:string;gameId:string;selection:unknown;separatePrefix:unknown;approvedBuild?:unknown;prefixAnchor?:unknown;defaultWine:string|undefined;arch?:string}):Promise<Readonly<GameRuntimeContext>> {
+export async function resolveGameRuntime(options:{runtimeRoot:string;dataRoot:string;defaultWine:string|undefined;arch?:string}&GameRuntimeParameters):Promise<Readonly<GameRuntimeContext>> {
const selection=gameRuntimeSelection(options.selection);
- if(!/^[A-Za-z0-9_-]{1,128}$/.test(options.gameId))throw Error('Invalid game prefix identity.');
+ prefixGameId(options.gameId);
+ const state={runtime:options.selection,runtimeBuild:options.runtimeBuild,runtimePrefixes:options.runtimePrefixes,runtimePrefixIdentity:options.runtimePrefixIdentity};
+ const identity=await captureGamePrefixIdentity({dataRoot:options.dataRoot,gameId:options.gameId,game:state});
+ const paths=runtimePrefixPaths(options.dataRoot,options.gameId,identity);
+ const frozenIdentity=Object.freeze({...identity}) as Readonly<RuntimePrefixIdentity>;
if(selection==='default') {
if(!options.defaultWine)throw Error('Select a default Wine / Proton runtime in Settings.');
const canonical=async(file:string)=>fs.realpath(file).catch(error=>{if(error.code==='ENOENT')return path.resolve(file);throw error;});
const managed=path.join(options.runtimeRoot,'variants');
const inside=(root:string,file:string)=>{const relative=path.relative(root,file);return Boolean(relative)&&!relative.startsWith('..'+path.sep)&&relative!=='..'&&!path.isAbsolute(relative);};
- if(inside(managed,options.defaultWine)||inside(await canonical(managed),await canonical(options.defaultWine)))throw Error('Select managed runtime families per game with a separate prefix.');
- return Object.freeze({selection,family:'default',winePath:options.defaultWine,dataRoot:options.dataRoot,
- compatibilityDataPath:path.join(options.dataRoot,'compatdata',options.gameId),legacyPrefixRoot:path.join(options.dataRoot,'prefixes',options.gameId)});
+ if(inside(managed,options.defaultWine)||inside(await canonical(managed),await canonical(options.defaultWine)))throw Error('Choose a managed runtime family for this game; a family runner cannot be the default Wine / Proton runtime.');
+ return Object.freeze({selection,identity:frozenIdentity,gameId:options.gameId,winePath:options.defaultWine,dataRoot:options.dataRoot,...paths});
}
- if(options.separatePrefix!==true)throw Error('Choose a separate runtime prefix before using this family. Existing local saves remain in the old prefix.');
const managed=await resolveRuntimeFamily(options.runtimeRoot,selection,options.arch);
- // Persisted pre-0.5 build metadata identifies an existing prefix, not its next runtime.
- const anchor=options.prefixAnchor!==undefined?runtimePrefixAnchor(options.prefixAnchor):options.approvedBuild!==undefined?{layout:'build' as const,origin:runtimeBuildApproval(options.approvedBuild)}:{layout:'family' as const};
- const root=path.join(options.dataRoot,'runtime-prefixes',selection,anchor.layout==='build'?anchor.origin.buildId:'prefixes',options.gameId);
- return Object.freeze({selection,family:selection,winePath:managed.winePath,dataRoot:options.dataRoot,managed,prefixAnchor:Object.freeze(anchor),
- compatibilityDataPath:path.join(root,'compatdata'),legacyPrefixRoot:path.join(root,'wine')});
+ return Object.freeze({selection,identity:frozenIdentity,gameId:options.gameId,winePath:managed.winePath,dataRoot:options.dataRoot,managed,...paths});
+}
+
+interface PrefixMarker { readonly [key:string]:unknown }
+/** Recorded prefix contract. The creating family is deliberately absent, so a
+ * family switch neither rewrites nor invalidates an existing marker. */
+function expectedMarker(context:Readonly<GameRuntimeContext>):PrefixMarker {
+ const managed=context.managed;
+ const contract=managed?{prefixSchema:managed.prefixSchema,arch:managed.arch}:{};
+ const identity=context.identity;
+ if(identity.layout==='game')return {schema:3,layout:'game',gameId:context.gameId,...contract};
+ if(identity.layout==='family')return {schema:2,layout:'family',family:identity.family,...contract};
+ return {schema:1,family:identity.family,buildId:identity.origin.buildId,sourceCommit:identity.origin.sourceCommit,manifestSha256:identity.origin.manifestSha256,...contract};
+}
+type MarkerContract={prefixSchema:number;arch:string}|'absent'|'invalid';
+function markerContract(marker:Record<string,unknown>):MarkerContract {
+ const prefixSchema=marker.prefixSchema,arch=marker.arch;
+ if(prefixSchema===undefined&&arch===undefined)return 'absent';
+ if(typeof prefixSchema!=='number'||!Number.isInteger(prefixSchema)||prefixSchema<1)return 'invalid';
+ if(typeof arch!=='string'||!/^[a-z0-9_]{1,16}$/.test(arch))return 'invalid';
+ return {prefixSchema,arch};
+}
+/**
+ * The origin fields of a marker must match exactly. The recorded prefix contract
+ * must always be well formed: legacy schema 1 and 2 markers must carry it, while
+ * schema 3 may omit it when the prefix was created without a managed payload. A
+ * current managed runner is compared against a recorded contract; a default Wine
+ * runner validates its shape but does not pretend to verify its values.
+ */
+function markerMatches(current:unknown,expected:PrefixMarker):boolean {
+ const marker=plainObject(current);
+ if(!marker||marker.schema!==expected.schema)return false;
+ for(const [key,value] of Object.entries(expected)) {
+ if(key==='prefixSchema'||key==='arch')continue;
+ if(marker[key]!==value)return false;
+ }
+ for(const key of Object.keys(marker)) if(!(key in expected)&&key!=='prefixSchema'&&key!=='arch')return false;
+ const contract=markerContract(marker);
+ if(contract==='invalid')return false;
+ if(contract==='absent')return expected.schema===3;
+ if(expected.prefixSchema===undefined)return true;
+ return contract.prefixSchema===expected.prefixSchema&&contract.arch===expected.arch;
}
/** No pfx/wineboot, copying, save migration or default pointer mutation. */
export async function bindRuntimePrefix(context:Readonly<GameRuntimeContext>):Promise<void> {
- const marker=path.join(context.compatibilityDataPath,'.nexus-runtime-family.json');
- if(context.managed) {
+ const marker=path.join(context.compatibilityDataPath,markerName);
+ // Experimental layouts keep the original protection even when a default Wine
+ // runner uses them; the canonical per-game prefix keeps its pre-0.5 behaviour.
+ if(context.managed||context.identity.layout!=='game') {
const relative=path.relative(context.dataRoot,context.compatibilityDataPath);
if(!relative||relative.startsWith('..')||path.isAbsolute(relative))throw Error('Unsafe runtime prefix location.');
let directory=context.dataRoot;
@@ -44,18 +210,22 @@ export async function bindRuntimePrefix(context:Readonly<GameRuntimeContext>):Pr
try{if(!(await fs.lstat(marker)).isFile())throw Error('Runtime prefix binding must be a regular file.');}
catch(error){if((error as NodeJS.ErrnoException).code!=='ENOENT')throw error;}
}
- const anchor=context.prefixAnchor;
- const expected=context.managed?(anchor?.layout==='build'?{schema:1,family:context.family,buildId:anchor.origin.buildId,sourceCommit:anchor.origin.sourceCommit,manifestSha256:anchor.origin.manifestSha256,prefixSchema:context.managed.prefixSchema,arch:context.managed.arch}:{schema:2,family:context.family,layout:'family',prefixSchema:context.managed.prefixSchema,arch:context.managed.arch}):undefined;
- try {
- const current=JSON.parse(await fs.readFile(marker,'utf8'));
- if(!expected) {if(current.family!=='default')throw Error('The default prefix belongs to another runtime family.');return;}
- if(Object.keys(current).length!==Object.keys(expected).length||Object.entries(expected).some(([key,value])=>current[key]!==value))throw Error('Runtime prefix binding mismatch. Existing prefix was preserved.');
+ const expected=expectedMarker(context);
+ const current=await readMarker(context.compatibilityDataPath);
+ if(current!==undefined) {
+ if(!markerMatches(current,expected))throw Error('Runtime prefix binding mismatch. Existing prefix was preserved.');
return;
- }catch(error){if((error as NodeJS.ErrnoException).code!=='ENOENT')throw error;}
- if(!expected)return; // Preserve the existing, unbound legacy default prefix.
- // An unbound nonempty experimental prefix has unknown provenance, never adopt it.
+ }
+ // A canonical prefix is a pre-0.5 default prefix: preserved unbound, never
+ // adopted into another location and never rewritten.
+ if(context.identity.layout==='game'&&await prefixPresent(context.compatibilityDataPath))return;
+ // An unbound experimental prefix has unknown provenance, never adopt it. This
+ // check applies to every runner, including the default Wine one.
const entries=await fs.readdir(context.compatibilityDataPath).catch(error=>{if(error.code==='ENOENT')return [];throw error;});
if(entries.length)throw Error('Experimental prefix has no runtime binding. Existing files were preserved.');
+ // A default Wine runner has no managed contract, so it never invents a marker
+ // for an experimental layout; an empty prefix stays unbound for a managed run.
+ if(!context.managed)return;
await fs.mkdir(context.compatibilityDataPath,{recursive:true,mode:0o700});
await fs.writeFile(marker,JSON.stringify(expected),{flag:'wx',mode:0o600});
}
diff --git a/src/main/runtime-settings.ts b/src/main/runtime-settings.ts
index 2f2f198..1ad142c 100644
--- a/src/main/runtime-settings.ts
+++ b/src/main/runtime-settings.ts
@@ -1,18 +1,67 @@
import type {Game} from '../shared/types.js';
import {gameRuntimeSelection,runtimePrefixAnchors,runtimeBuildApproval} from '../shared/runtime-selection.js';
import {resolveRuntimeFamily} from './runtime-families.js';
+import {captureGamePrefixIdentity} from './runtime-prefix-binding.js';
+/** `runtimeSeparatePrefix` is accepted for compatibility with older callers and
+ * stored state, but it never gates a family choice or a prefix location. */
export type RuntimeSettingsRequest=Partial<Pick<Game,'runtime'|'runtimeSeparatePrefix'>>;
-export async function approvedRuntimeSettings(current:Game,request:RuntimeSettingsRequest,runtimeRoot:string,resolve=resolveRuntimeFamily):Promise<Partial<Game>> {
+/** Component roots exactly as the launcher resolves them: the prefix store is
+ * the data root, and managed families live under its runtime root. */
+export interface RuntimeSettingsPaths { runtimeRoot:string; dataRoot:string }
+/**
+ * Capture the durable prefix identity of the state that exists before the
+ * change, then persist it atomically with the new selection. The chosen family
+ * only selects the runtime runner; it never selects the prefix or the saves.
+ * An ambiguous prefix history fails here, before anything is persisted.
+ */
+export async function approvedRuntimeSettings(current:Game,request:RuntimeSettingsRequest,paths:RuntimeSettingsPaths,resolve=resolveRuntimeFamily):Promise<Partial<Game>> {
const selection=gameRuntimeSelection('runtime' in request?request.runtime:current.runtime);
const separate='runtimeSeparatePrefix' in request?request.runtimeSeparatePrefix:current.runtimeSeparatePrefix;
if(separate!==undefined&&typeof separate!=='boolean')throw Error('Invalid runtime prefix choice.');
- const anchors=runtimePrefixAnchors(current.runtimePrefixes);
const previous=gameRuntimeSelection(current.runtime);
+ const anchors=runtimePrefixAnchors(current.runtimePrefixes);
+ // Keep the pre-0.5 build origin as backward-compatible path metadata.
if(previous!=='default'&&!anchors[previous]&&current.runtimeBuild)anchors[previous]={layout:'build',origin:runtimeBuildApproval(current.runtimeBuild)};
- if(selection==='default')return {runtime:selection,runtimeSeparatePrefix:false,runtimeBuild:undefined,runtimePrefixes:anchors};
- if(selection!==previous&&!anchors[selection]&&request.runtimeSeparatePrefix!==true)throw Error('Explicit separate prefix choice is required for a new runtime family.');
- if(separate!==true)throw Error('Explicit separate prefix choice is required. Existing local saves remain in the old prefix.');
- if(selection!==previous||current.runtimeSeparatePrefix!==true)await resolve(runtimeRoot,selection);
- anchors[selection]??={layout:'family'};
- return {runtime:selection,runtimeSeparatePrefix:true,runtimeBuild:undefined,runtimePrefixes:anchors};
+ const identity=await captureGamePrefixIdentity({dataRoot:paths.dataRoot,gameId:current.id,game:current});
+ // A new family must still be a verified installed build before it is persisted.
+ if(selection!=='default'&&selection!==previous)await resolve(paths.runtimeRoot,selection);
+ return {runtime:selection,runtimePrefixes:anchors,runtimePrefixIdentity:identity,runtimeBuild:undefined};
+}
+/** Fields whose values decide which prefix and saves a game uses. */
+export function runtimeIdentityScope(game:Partial<Game>):string {
+ return JSON.stringify([game.runtime,game.runtimePrefixIdentity,game.runtimeBuild,game.runtimePrefixes,game.runtimeSeparatePrefix]);
+}
+/** A held activity reservation: verifies idle again as the owner and releases. */
+export interface RuntimeSettingsAdmission { admit:()=>void; release:()=>void }
+/**
+ * Persist a runtime change as one admitted mutation.
+ *
+ * A real family change reserves the process activity slot before the first
+ * asynchronous step and keeps it through the persisted write, so a launch or a
+ * component update cannot enter at any await in between. The rerun of the
+ * admission is only an assertion that our own reservation is still valid; it is
+ * not the lock. The persisted record is checked as well, so a change that
+ * happened before the reservation cannot be overwritten.
+ */
+export async function guardedRuntimeSettings(options:{
+ current:Game;request:RuntimeSettingsRequest;paths:RuntimeSettingsPaths;changing:boolean;
+ reserve:()=>RuntimeSettingsAdmission;read:()=>Game|undefined;
+ persist:(patch:Partial<Game>)=>Promise<Game>;
+ approve?:(current:Game,request:RuntimeSettingsRequest,paths:RuntimeSettingsPaths)=>Promise<Partial<Game>>;
+}):Promise<Game> {
+ const approve=options.approve??((current,request,paths)=>approvedRuntimeSettings(current,request,paths));
+ const write=async(approved:Partial<Game>):Promise<Game>=>{
+ const latest=options.read();
+ if(!latest||runtimeIdentityScope(latest)!==runtimeIdentityScope(options.current))throw Error('The game runtime selection changed. Try again.');
+ return options.persist(approved);
+ };
+ // An unchanged runtime still persists the captured identity, and it must not
+ // block an unrelated running game.
+ if(!options.changing)return write(await approve(options.current,options.request,options.paths));
+ const admission=options.reserve();
+ try {
+ const approved=await approve(options.current,options.request,options.paths);
+ admission.admit();
+ return await write(approved);
+ } finally { admission.release(); }
}
diff --git a/src/main/store.ts b/src/main/store.ts
index 30c2192..829ed43 100644
--- a/src/main/store.ts
+++ b/src/main/store.ts
@@ -1,4 +1,4 @@
-import {gameRuntimeSelection,runtimeBuildApproval,runtimePrefixAnchors} from '../shared/runtime-selection.js';
+import {gameRuntimeSelection,runtimeBuildApproval,runtimePrefixAnchors,runtimePrefixIdentity} from '../shared/runtime-selection.js';
import { createHash } from 'node:crypto';
import { promises as fs } from 'node:fs';
import os from 'node:os';
@@ -114,6 +114,7 @@ export class StateStore {
if ('runtime' in patch) patch.runtime = gameRuntimeSelection(patch.runtime);
if ('runtimeSeparatePrefix' in patch && typeof patch.runtimeSeparatePrefix !== 'boolean') throw Error('Invalid runtime prefix choice.');
if ('runtimePrefixes' in patch) patch.runtimePrefixes=runtimePrefixAnchors(patch.runtimePrefixes);
+ if ('runtimePrefixIdentity' in patch) patch.runtimePrefixIdentity=patch.runtimePrefixIdentity===undefined?undefined:runtimePrefixIdentity(patch.runtimePrefixIdentity);
if ('runtimeBuild' in patch && patch.runtimeBuild !== undefined) patch.runtimeBuild=runtimeBuildApproval(patch.runtimeBuild);
Object.assign(game, patch);
await this.save();
diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx
index 0a4c394..33b1857 100644
--- a/src/renderer/App.tsx
+++ b/src/renderer/App.tsx
@@ -230,7 +230,7 @@ function useGameLaunchOptions(game: Game | undefined, data: AppSnapshot): GameLa
.then((value) => { if (!cancelled) setOptions(value); })
.catch((error) => { if (!cancelled) setOptions({ cloudSaves: false, cloudReason: errorMessage(error), vcInstall: false, vcReason: errorMessage(error) }); });
return () => { cancelled = true; };
- }, [game?.id, game?.runtime, game?.runtimeSeparatePrefix, game?.runtimeBuild?.buildId, game?.runtimeBuild?.manifestSha256, JSON.stringify(game?.runtimePrefixes), data.runtime.variants?.map(item=>item.id+':'+item.buildId).join(','), data.settings.winePath, data.settings.runtimeRoot, data.runtime.winePath, data.backend.binaryPath, data.backend.commit, data.backend.available]);
+ }, [game?.id, game?.runtime, game?.runtimeSeparatePrefix, game?.runtimePrefixIdentity, game?.runtimeBuild?.buildId, game?.runtimeBuild?.manifestSha256, JSON.stringify(game?.runtimePrefixes), data.runtime.variants?.map(item=>item.id+':'+item.buildId).join(','), data.settings.winePath, data.settings.runtimeRoot, data.runtime.winePath, data.backend.binaryPath, data.backend.commit, data.backend.available]);
return options;
}
@@ -694,7 +694,6 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,
const [editTitle, setEditTitle] = useState('');
const [editLocale, setEditLocale] = useState('');
const [editRuntime,setEditRuntime]=useState<GameRuntimeSelection>('default');
- const [editSeparatePrefix,setEditSeparatePrefix]=useState(false);
const [runtimeChoices,setRuntimeChoices]=useState<InstalledRuntimeFamily[]>(data.runtime.variants??[]);
const runtimeChoicesKey=JSON.stringify(data.runtime.variants??[]);
useEffect(()=>setRuntimeChoices(data.runtime.variants??[]),[runtimeChoicesKey]);
@@ -776,7 +775,6 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,
setEditTitle(game.title);
setEditLocale(game.locale ?? '');
setEditRuntime(game.runtime ?? 'default');
- setEditSeparatePrefix(game.runtimeSeparatePrefix===true);
setEditTools({ ...defaultLaunchTools, ...game.launchTools });
setLocaleOptions([]);
const request = ++localeRequest.current;
@@ -792,7 +790,7 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,
if (!dialogGame) return;
setDialogBusy(true);
try {
- await window.launcher.updateGame(dialogGame.id, { title: editTitle.trim(), locale: editLocale, launchTools: normalizeLaunchTools(editTools), runtime:editRuntime, runtimeSeparatePrefix:editSeparatePrefix });
+ await window.launcher.updateGame(dialogGame.id, { title: editTitle.trim(), locale: editLocale, launchTools: normalizeLaunchTools(editTools), runtime:editRuntime });
toast({ kind: 'success', message: ui("ui.game_settings_saved_7f466a5") });
setDialogGame(undefined);
} catch (error) { toast({ kind: 'error', message: errorMessage(error) }); }
@@ -903,7 +901,7 @@ export function LibraryPage({ data, toast, filters, onFiltersChange, selection,
<h2>{ui("ui.game_settings_fece860")}</h2>
<label>{ui("ui.display_name_2b7f6a8")}<input data-gamepad-initial required value={editTitle} onChange={(event) => setEditTitle(event.target.value)} /></label>
<GameLanguage value={editLocale} locales={localeOptions} onChange={setEditLocale} />
- <GameRuntimeFields value={editRuntime} separate={editSeparatePrefix} installed={runtimeChoices} change={value=>{setEditRuntime(value);setEditSeparatePrefix(value===(modalGame.runtime??'default')?modalGame.runtimeSeparatePrefix===true:Boolean(value!=='default'&&modalGame.runtimePrefixes?.[value]));}} changeSeparate={setEditSeparatePrefix}/>
+ <GameRuntimeFields value={editRuntime} installed={runtimeChoices} change={setEditRuntime}/>
<GameLaunchToolFields value={editTools} change={setEditTools} />
<div className="dialog-actions"><button type="button" className="secondary" disabled={dialogBusy} data-gamepad-cancel onClick={() => setDialogGame(undefined)}>{ui("ui.cancel_19766ed")}</button><button className="primary" disabled={dialogBusy || !editTitle.trim()}><Check />{ui("ui.save_1509f56")}</button></div>
</form>}
diff --git a/src/renderer/GameRuntimeFields.tsx b/src/renderer/GameRuntimeFields.tsx
index db8c896..ab6caf2 100644
--- a/src/renderer/GameRuntimeFields.tsx
+++ b/src/renderer/GameRuntimeFields.tsx
@@ -1,17 +1,15 @@
-import {CheckField} from './CheckField';
import {ui} from './i18n';
import {runtimeFamilyLabels,type GameRuntimeSelection,type InstalledRuntimeFamily} from '../shared/runtime-selection';
-export function GameRuntimeFields({value,separate,installed,change,changeSeparate}:{value:GameRuntimeSelection;separate:boolean;installed:InstalledRuntimeFamily[];change:(value:GameRuntimeSelection)=>void;changeSeparate:(value:boolean)=>void}) {
+
+/** One explicit choice: the default runtime or an installed managed family.
+ * The game keeps one stable prefix that its own runtime identity owns, so
+ * choosing a family needs no separate prefix consent. */
+export function GameRuntimeFields({value,installed,change}:{value:GameRuntimeSelection;installed:InstalledRuntimeFamily[];change:(value:GameRuntimeSelection)=>void}) {
const current=installed.find(item=>item.id===value);
const missing=value!=='default'&&!current;
- return <>
- <label>{ui('runtime.game_runtime')}<select value={value} onChange={event=>change(event.target.value as GameRuntimeSelection)}>
- <option value="default">{ui('runtime.use_default')}</option>
- {installed.map(item=><option key={item.id} value={item.id}>{item.label}</option>)}
- {missing?<option value={value} disabled>{ui('runtime.unavailable',{name:runtimeFamilyLabels[value as keyof typeof runtimeFamilyLabels]??String(value)})}</option>:null}
- </select></label>
- {value!=='default'?<>
- <CheckField required checked={separate} onChange={event=>changeSeparate(event.target.checked)} label={ui('runtime.separate_prefix')} description={ui('runtime.prefix_warning')}/>
- </>:null}
- </>;
+ return <label>{ui('runtime.game_runtime')}<select value={value} onChange={event=>change(event.target.value as GameRuntimeSelection)}>
+ <option value="default">{ui('runtime.use_default')}</option>
+ {installed.map(item=><option key={item.id} value={item.id}>{runtimeFamilyLabels[item.id]}</option>)}
+ {missing?<option value={value} disabled>{ui('runtime.unavailable',{name:runtimeFamilyLabels[value as keyof typeof runtimeFamilyLabels]??String(value)})}</option>:null}
+ </select></label>;
}
diff --git a/src/renderer/game-runtime-fields.test.tsx b/src/renderer/game-runtime-fields.test.tsx
index e321285..dbdb650 100644
--- a/src/renderer/game-runtime-fields.test.tsx
+++ b/src/renderer/game-runtime-fields.test.tsx
@@ -1,25 +1,24 @@
-import {gameRuntimeAvailable} from '../shared/runtime-selection';
import {expect,it} from 'vitest';
import {renderToStaticMarkup} from 'react-dom/server';
import {GameRuntimeFields} from './GameRuntimeFields';
+import type {InstalledRuntimeFamily} from '../shared/runtime-selection';
const change=()=>{};
-it('offers only default when no verified variants are installed, never an unbuilt CachyOS option',()=>{
- const html=renderToStaticMarkup(<GameRuntimeFields value="default" separate={false} installed={[]} change={change} changeSeparate={change}/>);
+const installed:InstalledRuntimeFamily[]=[
+ {id:'nexus',label:'Standard',buildId:'a'.repeat(64),sourceCommit:'b'.repeat(40),manifestSha256:'c'.repeat(64)},
+ {id:'nexus-cachyos',label:'CachyOS',buildId:'d'.repeat(64),sourceCommit:'e'.repeat(40),manifestSha256:'f'.repeat(64)},
+];
+it('offers only the default runtime when no verified family is installed, never an unbuilt CachyOS option',()=>{
+ const html=renderToStaticMarkup(<GameRuntimeFields value="default" installed={[]} change={change}/>);
expect(html.match(/<option/g)).toHaveLength(1);expect(html).not.toContain('CachyOS');expect(html).toContain('Use default runtime');
});
-it('lists verified families with explicit separate-prefix acknowledgment and save warning',()=>{
- const html=renderToStaticMarkup(<GameRuntimeFields value="nexus-cachyos" separate={false} installed={[{id:'nexus-cachyos',label:'CachyOS',buildId:'a'.repeat(64),sourceCommit:'b'.repeat(40),manifestSha256:'c'.repeat(64)}]} change={change} changeSeparate={change}/>);
- expect(html).toContain('CachyOS');expect(html).toMatch(/type="checkbox" required/);expect(html).toContain('class="check-input"');const help=html.match(/aria-describedby="([^"]+)"/)?.[1];expect(help).toBeTruthy();expect(html).toContain('<small id="'+help+'">');expect(html).toContain('Existing local saves stay in the old prefix');expect(html).toContain('Updates within this family reuse the same prefix and local saves');expect(html).not.toContain('each runtime build');expect(html).not.toContain('this runtime build');expect(html).not.toContain('checked=""');
+it('lists the default, Standard and CachyOS as plain choices without a separate-prefix consent step',()=>{
+ const html=renderToStaticMarkup(<GameRuntimeFields value="nexus-cachyos" installed={installed} change={change}/>);
+ expect(html.match(/<option/g)).toHaveLength(3);
+ expect(html).toContain('>Standard</option>');expect(html).toContain('>CachyOS</option>');
+ expect(html).not.toContain('type="checkbox"');expect(html).not.toContain('required=""');
+ expect(html).not.toContain('separate prefix');expect(html).not.toContain('local saves');
});
-it('shows a missing persisted selection as disabled rather than falling back',()=>{
- const html=renderToStaticMarkup(<GameRuntimeFields value="nexus-cachyos" separate installed={[]} change={change} changeSeparate={change}/>);
- expect(html).toMatch(/value="nexus-cachyos" disabled="" selected=""/);expect(html).toContain('(unavailable)');
-});
-
-it('allows a verified selected family without a default and never borrows default availability for a missing family',()=>{
- const installed=[{id:'nexus-cachyos' as const,label:'Experimental',buildId:'a'.repeat(64),sourceCommit:'b'.repeat(40),manifestSha256:'c'.repeat(64)}];
- expect(gameRuntimeAvailable('nexus-cachyos',true,false,installed)).toBe(true);
- expect(gameRuntimeAvailable('nexus-cachyos',true,true,[])).toBe(false);
- expect(gameRuntimeAvailable('nexus-cachyos',false,true,installed)).toBe(false);
- expect(gameRuntimeAvailable(undefined,false,true,[])).toBe(true);
+it('shows a missing persisted selection as unavailable rather than falling back to another runtime',()=>{
+ const html=renderToStaticMarkup(<GameRuntimeFields value="nexus-cachyos" installed={[]} change={change}/>);
+ expect(html).toMatch(/value="nexus-cachyos" disabled="" selected=""/);expect(html).toContain('CachyOS (unavailable)');
});
diff --git a/src/renderer/game-runtime-settings.test.tsx b/src/renderer/game-runtime-settings.test.tsx
index ee27aa1..a1830d4 100644
--- a/src/renderer/game-runtime-settings.test.tsx
+++ b/src/renderer/game-runtime-settings.test.tsx
@@ -9,7 +9,6 @@ let root:Root,data:ReturnType<typeof demoSnapshot>;
const family='nexus-cachyos';
const a={buildId:'a'.repeat(64),manifestSha256:'b'.repeat(64),sourceCommit:'c'.repeat(40)};
const b={buildId:'d'.repeat(64),manifestSha256:'e'.repeat(64),sourceCommit:'f'.repeat(40)};
-const c={buildId:'1'.repeat(64),manifestSha256:'2'.repeat(64),sourceCommit:'3'.repeat(40)};
const installed=(build:typeof a):InstalledRuntimeFamily=>({id:family,label:'CachyOS',...build});
const render=async()=>{await act(async()=>root.render(<LibraryPage data={data} toast={()=>{}}/>));};
const click=async(element:Element)=>{await act(async()=>(element as HTMLElement).click());};
@@ -18,7 +17,8 @@ async function openSettings() {
const settings=[...document.querySelectorAll('.game-context-menu button')].find(button=>button.textContent==='Game settings')!;
await click(settings);
}
-const consent=()=>document.querySelector<HTMLInputElement>('[role="dialog"] input[type="checkbox"][required]')!;
+const runtimeSelect=()=>[...document.querySelectorAll<HTMLSelectElement>('[role="dialog"] select')].find(node=>[...node.options].some(option=>option.value===family))!;
+const choose=async(value:string)=>{const select=runtimeSelect();await act(async()=>{select.value=value;select.dispatchEvent(new Event('change',{bubbles:true}));});};
const save=()=>click(document.querySelector('[role="dialog"] button.primary')!);
beforeEach(async()=>{
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT',true);
@@ -29,23 +29,29 @@ beforeEach(async()=>{
document.body.innerHTML='<div id="root"></div>';root=createRoot(document.getElementById('root')!);await render();
});
afterEach(async()=>{await act(async()=>root.unmount());vi.restoreAllMocks();vi.unstubAllGlobals();document.body.innerHTML='';});
-it('retains family consent when a newer installed build is discovered without a new approval action',async()=>{
- await openSettings();expect(consent().checked).toBe(true);expect(document.querySelector('[role="alert"]')).toBeNull();
- await save();expect(window.launcher.updateGame).toHaveBeenCalledWith(data.games[0].id,expect.objectContaining({runtime:family,runtimeSeparatePrefix:true}));expect(vi.mocked(window.launcher.updateGame).mock.calls[0][1]).not.toHaveProperty('runtimeApproveBuild');
+it('shows the saved family as a plain runtime choice without a separate-prefix checkbox',async()=>{
+ await openSettings();expect(runtimeSelect().value).toBe(family);
+ expect(document.querySelector('[role="dialog"] input[type="checkbox"][required]')).toBeNull();
+ expect(document.querySelector('[role="dialog"]')!.textContent).not.toContain('separate prefix');
+ await save();
+ expect(window.launcher.updateGame).toHaveBeenCalledWith(data.games[0].id,expect.objectContaining({runtime:family}));
+ expect(vi.mocked(window.launcher.updateGame).mock.calls[0][1]).not.toHaveProperty('runtimeSeparatePrefix');
});
-it('keeps consent during B to C update while the form is open',async()=>{
- await openSettings();data.runtime.variants=[installed(c)];await render();expect(consent().checked).toBe(true);await save();expect(window.launcher.updateGame).toHaveBeenCalledWith(data.games[0].id,expect.objectContaining({runtimeSeparatePrefix:true}));
-});
-it('retains consent after reopening and local family refresh',async()=>{
- data.runtime.variants=[installed(a)];await render();vi.mocked(window.launcher.getRuntimeFamilies).mockResolvedValue([installed(b)]);await openSettings();expect(consent().checked).toBe(true);await click(document.querySelector('[role="dialog"] [data-gamepad-cancel]')!);await openSettings();expect(consent().checked).toBe(true);
-});
-it('requires separate prefix consent when first choosing another family',async()=>{
+it('saves a newly chosen family without a consent action and without an explicit prefix field',async()=>{
data.games=[{...data.games[0],runtime:'default',runtimeSeparatePrefix:false,runtimeBuild:undefined}];await render();await openSettings();
- const select=[...document.querySelectorAll<HTMLSelectElement>('[role="dialog"] select')].find(node=>[...node.options].some(option=>option.value===family))!;
- await act(async()=>{select.value=family;select.dispatchEvent(new Event('change',{bubbles:true}));});expect(consent().checked).toBe(false);await click(consent());await save();expect(window.launcher.updateGame).toHaveBeenCalledWith(data.games[0].id,expect.objectContaining({runtime:family,runtimeSeparatePrefix:true}));
+ expect(runtimeSelect().value).toBe('default');
+ await choose(family);
+ await save();
+ expect(window.launcher.updateGame).toHaveBeenCalledWith(data.games[0].id,expect.objectContaining({runtime:family}));
+ expect(vi.mocked(window.launcher.updateGame).mock.calls[0][1]).not.toHaveProperty('runtimeSeparatePrefix');
+});
+it('keeps the family choice when a newer installed build is discovered while the form is open',async()=>{
+ await openSettings();data.runtime.variants=[installed(b)];await render();
+ expect(runtimeSelect().value).toBe(family);await save();
+ expect(window.launcher.updateGame).toHaveBeenCalledWith(data.games[0].id,expect.objectContaining({runtime:family}));
});
-it('returning to a previously used family retains its saved prefix choice',async()=>{
- data.games=[{...data.games[0],runtime:'default',runtimeSeparatePrefix:false,runtimePrefixes:{[family]:{layout:'build',origin:a}}}];await render();await openSettings();
- const select=[...document.querySelectorAll<HTMLSelectElement>('[role="dialog"] select')].find(node=>[...node.options].some(option=>option.value===family))!;
- await act(async()=>{select.value=family;select.dispatchEvent(new Event('change',{bubbles:true}));});expect(consent().checked).toBe(true);
+it('returns the choice to the default runtime without leftover consent state',async()=>{
+ await openSettings();await choose('default');await save();
+ expect(window.launcher.updateGame).toHaveBeenCalledWith(data.games[0].id,expect.objectContaining({runtime:'default'}));
+ expect(vi.mocked(window.launcher.updateGame).mock.calls[0][1]).not.toHaveProperty('runtimeSeparatePrefix');
});
diff --git a/src/renderer/useGameRuntimeReady.ts b/src/renderer/useGameRuntimeReady.ts
index 7b6c268..25a6b29 100644
--- a/src/renderer/useGameRuntimeReady.ts
+++ b/src/renderer/useGameRuntimeReady.ts
@@ -4,7 +4,7 @@ import type {AppSnapshot,Game} from '../shared/types';
* 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,game?.runtimePrefixes,data.settings.runtimeRoot,data.settings.winePath,data.runtime.winePath,data.runtime.managedRevision,(data.runtime.variants??[]).map(item=>[item.id,item.buildId,item.manifestSha256,item.sourceCommit])]);
+ const scope=JSON.stringify([game?.id,game?.runtime,game?.runtimePrefixIdentity,game?.runtimeSeparatePrefix,game?.runtimeBuild?.buildId,game?.runtimeBuild?.manifestSha256,game?.runtimeBuild?.sourceCommit,game?.runtimePrefixes,data.settings.runtimeRoot,data.settings.winePath,data.runtime.winePath,data.runtime.managedRevision,(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;
diff --git a/src/shared/runtime-selection.ts b/src/shared/runtime-selection.ts
index 269e5cf..2308ad9 100644
--- a/src/shared/runtime-selection.ts
+++ b/src/shared/runtime-selection.ts
@@ -27,10 +27,12 @@ export interface InstalledRuntimeFamily {
* launch, approval or selection input. */
displayWinePath?: string;
}
-/** A chosen managed family never borrows the global runtime's availability. */
-export function gameRuntimeAvailable(selection:unknown,separatePrefix:unknown,defaultAvailable:boolean,installed:readonly InstalledRuntimeFamily[]):boolean {
+/** A chosen managed family never borrows the global runtime's availability.
+ * A game prefix is stable across families, so no separate-prefix consent is a
+ * precondition for choosing a family. */
+export function gameRuntimeAvailable(selection:unknown,defaultAvailable:boolean,installed:readonly InstalledRuntimeFamily[]):boolean {
if(selection===undefined||selection==='default')return defaultAvailable;
- return separatePrefix===true&&runtimeFamilies.includes(selection as RuntimeFamily)&&installed.some(item=>item.id===selection);
+ return runtimeFamilies.includes(selection as RuntimeFamily)&&installed.some(item=>item.id===selection);
}
/** Prefix identity survives family updates and switching away/back. Build origin is compatibility metadata, never a runtime pin. */
@@ -53,3 +55,50 @@ export function runtimePrefixAnchors(value:unknown):RuntimePrefixAnchors {
}
return result;
}
+
+/**
+ * Durable per-game prefix location, independent of the currently selected
+ * runtime family. It is captured once from the state that existed before a
+ * selection change and only selects a backend-owned path layout, so no renderer
+ * value can name a directory:
+ * - `game`: one canonical per-game prefix, the pre-0.5 default location;
+ * - `family`: an existing experimental family-wide prefix (runtime-prefixes/<family>/prefixes);
+ * - `build`: an existing build-specific prefix (runtime-prefixes/<family>/<buildId>).
+ * The layout origin is path metadata only. It never pins a runtime build and is
+ * not rewritten when the family changes.
+ */
+export type RuntimePrefixOrigin =
+ | {layout:'game'}
+ | {layout:'family';family:RuntimeFamily}
+ | {layout:'build';family:RuntimeFamily;origin:RuntimeBuildApproval};
+export type RuntimePrefixIdentity = RuntimePrefixOrigin;
+/** Persisted game fields that can describe where an existing prefix lives. */
+export interface RuntimePrefixState {
+ runtime?:unknown; runtimeBuild?:unknown; runtimePrefixes?:unknown; runtimePrefixIdentity?:unknown;
+}
+function runtimeFamilyId(value:unknown):RuntimeFamily {
+ if(runtimeFamilies.includes(value as RuntimeFamily))return value as RuntimeFamily;
+ throw Error('Invalid runtime prefix identity.');
+}
+export function runtimePrefixOrigin(value:unknown):RuntimePrefixOrigin {
+ if(!value||typeof value!=='object'||Array.isArray(value))throw Error('Invalid runtime prefix identity.');
+ const item=value as RuntimePrefixOrigin;
+ if(item.layout==='game')return {layout:'game'};
+ if(item.layout==='family')return {layout:'family',family:runtimeFamilyId(item.family)};
+ if(item.layout==='build')return {layout:'build',family:runtimeFamilyId(item.family),origin:runtimeBuildApproval(item.origin)};
+ throw Error('Invalid runtime prefix identity.');
+}
+/** Validates a persisted identity. Unknown layouts, families or build receipts fail closed. */
+export function runtimePrefixIdentity(value:unknown):RuntimePrefixIdentity {
+ return runtimePrefixOrigin(value);
+}
+/** Origin of the prefix that the persisted selection used before any change. */
+export function legacyRuntimePrefixOrigin(state:RuntimePrefixState):RuntimePrefixOrigin {
+ const selection=gameRuntimeSelection(state.runtime);
+ if(selection==='default')return {layout:'game'};
+ const anchor=runtimePrefixAnchors(state.runtimePrefixes)[selection];
+ if(anchor?.layout==='build')return {layout:'build',family:selection,origin:anchor.origin};
+ if(anchor)return {layout:'family',family:selection};
+ if(state.runtimeBuild!==undefined)return {layout:'build',family:selection,origin:runtimeBuildApproval(state.runtimeBuild)};
+ return {layout:'family',family:selection};
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 752852d..07e9ab0 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1,4 +1,4 @@
-import type {RuntimeFamily,GameRuntimeSelection,InstalledRuntimeFamily,RuntimeBuildApproval,RuntimePrefixAnchors} from './runtime-selection.js';
+import type {RuntimeFamily,GameRuntimeSelection,InstalledRuntimeFamily,RuntimeBuildApproval,RuntimePrefixAnchors,RuntimePrefixIdentity} from './runtime-selection.js';
export type Page = 'home' | 'store' | 'library' | 'downloads' | 'settings' | 'social';
export interface BackendCapabilities {
@@ -141,7 +141,11 @@ export interface Game {
runtime?: GameRuntimeSelection;
runtimeSeparatePrefix?: boolean;
runtimeBuild?: RuntimeBuildApproval; // Old prefix origin only, never a launch pin.
- runtimePrefixes?: RuntimePrefixAnchors;
+ runtimePrefixes?: RuntimePrefixAnchors; // Legacy per-family path metadata, never a launch pin.
+ /** Backend-owned durable prefix location. Captured from the persisted state
+ * before a selection change; it survives family switches and reloads and is
+ * never accepted from the renderer. */
+ runtimePrefixIdentity?: RuntimePrefixIdentity;
launchArgs?: string;
launchTools?: GameLaunchTools;
locale?: string;