A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.
TypeScript amazon-primeelectronepic-games-launcherepic-games-storeepic-storegaminggoggog-galaxyheroic-games-launcherlinuxplay-gamesprotonsteamwine
[Fix] steam platform pin and redownload on switch (#6159)
Drackrathfbdae1b61399
diff --git a/public/locales/en/translation.json b/public/locales/en/translation.jsonindex d5856e730..96713cdd1 100644--- a/public/locales/en/translation.json+++ b/public/locales/en/translation.json@@ -120,6 +120,9 @@"running-gamemode": "A one-time Steam restart is required before Heroic can manage Steam shortcuts on this device. Restart Steam and try again."},"steam-move-no-library": "Choose a Steam library folder to move the game to.",+ "steam-platform-switch": {+ "title": "Could not switch the game version"+ },"steam-running": "Steam is running. Close Steam, then try again.","title": "Error","uncaught-exception": {@@ -1558,9 +1561,13 @@"missingRuntime": "Steam runtime not installed","native": "Native","none": "No Steam",+ "platformSwitchNote": "Switching platform downloads it on next launch.",+ "platformSwitchNoteNow": "Switching platform downloads it when you close the settings.","runtime": "In-Wine Steam runtime","title": "Game version to launch"},+ "steamPlatformSwitchInstall": "Download Steam game versions when switching",+ "steamPlatformSwitchInstall-description": "Start the download when you close the game settings after picking the Linux or Windows version of a Steam game, instead of on its next launch","steamRuntime": {"defaultLabel": "Default Steam runtime (native Linux games)","label": "Steam runtime (native Linux games)",diff --git a/src/backend/downloadmanager/__tests__/downloadqueue.test.ts b/src/backend/downloadmanager/__tests__/downloadqueue.test.tsindex c6463cbce..f7377fced 100644--- a/src/backend/downloadmanager/__tests__/downloadqueue.test.ts+++ b/src/backend/downloadmanager/__tests__/downloadqueue.test.ts@@ -220,6 +220,122 @@ describe('auto-updates', () => {})})+describe('a download a backend runs itself', () => {+ it('is the current element until it finishes, then history', async () => {+ const finish = dm.trackExternalDownload(element('factorio'))!+ await flush()++ expect(queued()).toEqual(['factorio'])+ expect(dm.isRunning()).toBe(true)+ // The queue never starts its own install for it+ expect(install).not.toHaveBeenCalled()++ await finish('done')++ expect(queued()).toEqual([])+ expect(dm.getQueueInformation().finished).toEqual([+ expect.objectContaining({+ status: 'done',+ params: expect.objectContaining({ appName: 'factorio' })+ })+ ])+ })++ it('goes to history when it ends while waiting behind another', async () => {+ await dm.addToQueue(element('other'))+ await flush()+ const finish = dm.trackExternalDownload(element('factorio'))!+ await flush()+ expect(queued()).toEqual(['other', 'factorio'])++ await finish('error')++ expect(queued()).toEqual(['other'])+ expect(dm.getQueueInformation().finished).toEqual([+ expect.objectContaining({ status: 'error' })+ ])+ expect(dm.isRunning()).toBe(true)+ })++ it('resumes as a normal install after a pause', async () => {+ const finish = dm.trackExternalDownload(element('factorio'))!+ await flush()+ dm.pauseCurrentDownload()+ await finish('abort')+ await flush()++ expect(dm.isPaused()).toBe(true)+ expect(queued()).toEqual(['factorio'])++ await dm.resumeCurrentDownload()+ await flush()+ expect(install).toHaveBeenLastCalledWith(+ expect.objectContaining({ appName: 'factorio' })+ )+ })++ it('refuses a second one while the first is pending', async () => {+ const first = dm.trackExternalDownload(element('factorio'))!+ await flush()++ expect(dm.trackExternalDownload(element('factorio'))).toBeUndefined()++ await dm.addToQueue(element('next'))+ await first('done')+ await flush()+ // The queue moved on+ expect(queued()).toEqual(['next'])+ expect(install).toHaveBeenLastCalledWith(+ expect.objectContaining({ appName: 'next' })+ )+ })++ it('leaves a queued install or update of the game alone', async () => {+ await dm.addToQueue(element('other'))+ await dm.addToQueue(element('factorio', 'update'))+ await flush()++ expect(dm.trackExternalDownload(element('factorio'))).toBeUndefined()++ pending.get('other')!('done')+ await flush()+ // The real update still runs+ expect(update).toHaveBeenLastCalledWith(+ expect.objectContaining({ appName: 'factorio' })+ )+ })++ it('keeps a cancelled one out of the history', async () => {+ const { callAbortController } =+ await import('backend/utils/aborthandler/aborthandler')+ await dm.addToQueue(element('other'))+ await flush()+ const finish = dm.trackExternalDownload(element('factorio'))!+ await flush()++ dm.cancelQueuedDownload('factorio')+ expect(callAbortController).toHaveBeenCalledWith('factorio')+ await finish('abort')++ expect(queued()).toEqual(['other'])+ expect(dm.getQueueInformation().finished).toEqual([])+ })++ it('does not stall the queue when cancelled while running', async () => {+ const finish = dm.trackExternalDownload(element('factorio'))!+ await flush()+ await dm.addToQueue(element('next'))++ dm.cancelCurrentDownload({})+ await finish('abort')+ await flush()++ expect(install).toHaveBeenLastCalledWith(+ expect.objectContaining({ appName: 'next' })+ )+ })+})+describe('queue size bookkeeping', () => {it('stores the numeric download size for the row', async () => {const { libraryManagerMap } = await import('backend/storeManagers')diff --git a/src/backend/downloadmanager/downloadqueue.ts b/src/backend/downloadmanager/downloadqueue.tsindex 8ca19cd6d..2394e2d21 100644--- a/src/backend/downloadmanager/downloadqueue.ts+++ b/src/backend/downloadmanager/downloadqueue.ts@@ -36,6 +36,21 @@ let queueLoop: Promise<void> | null = nullconst failedUpdates = new Set<string>()const updateKey = (appName: string, runner: string) => `${runner}:${appName}`+interface ExternalDownload {+ // Settles with the download's outcome.+ finish: (status: DMStatus) => void+ done: Promise<DMStatus>+ // Settles once the queue recorded it.+ recorded: () => void+ whenRecorded: Promise<void>+ // Queue loop awaits `done`.+ claimed: boolean+ // User cancelled; skip the history.+ cancelled: boolean+}+// Downloads a backend runs itself; the queue only shows them.+const externalDownloads = new Map<string, ExternalDownload>()+onConnectivityChange((status) => {if (status === 'offline' && isRunning()) {logInfo('System offline, auto-pausing downloads', LogPrefix.DownloadManager)@@ -89,6 +104,82 @@ function addToFinished(element: DMQueueElement, status: DMStatus) {#### Public ####*/+/**+ * Show a download a backend runs itself (e.g. a game version fetched while+ * starting the game) as a queue element, with the progress it reports through+ * `sendProgressUpdate`. Returns the function to call with the outcome; it+ * resolves once the element moved to the finished downloads.+ *+ * Returns undefined, tracking nothing, while the game already has a queued+ * download (its own or a tracked one): that one keeps its place.+ *+ * A paused element stays queued and resumes as a normal install.+ */+function trackExternalDownload(+ element: DMQueueElement+): ((status: DMStatus) => Promise<void>) | undefined {+ const { appName, runner } = element.params+ const key = updateKey(appName, runner)++ const elements = downloadManager.get('queue', [])+ if (+ externalDownloads.has(key) ||+ elements.some(+ (el) => updateKey(el.params.appName, el.params.runner) === key+ )+ ) {+ logWarning(+ [appName, 'already has a queued download, not tracking another'],+ LogPrefix.DownloadManager+ )+ return undefined+ }++ let finish: ExternalDownload['finish'] = () => undefined+ const done = new Promise<DMStatus>((resolve) => {+ finish = resolve+ })+ let recorded: ExternalDownload['recorded'] = () => undefined+ const whenRecorded = new Promise<void>((resolve) => {+ recorded = resolve+ })+ const entry: ExternalDownload = {+ finish,+ done,+ recorded,+ whenRecorded,+ claimed: false,+ cancelled: false+ }+ externalDownloads.set(key, entry)++ elements.push(element)+ downloadManager.set('queue', elements)+ sendFrontendMessage('changedDMQueueInformation', elements, queueState)+ if (isIdle() && !isPaused()) {+ void initQueue()+ }++ let settled = false+ return async (status: DMStatus) => {+ if (settled) return+ settled = true+ if (externalDownloads.get(key) === entry) externalDownloads.delete(key)++ if (entry.claimed) {+ // The queue loop records it.+ entry.finish(status)+ await entry.whenRecorded+ return+ }+ // Cancelled before reaching the front.+ if (entry.cancelled) return+ // Never reached the front of the queue.+ addToFinished({ ...element, endTime: Date.now() }, status)+ removeFromQueue(appName)+ }+}+function initQueue(): Promise<void> {queueLoop ??= runQueue().finally(() => {queueLoop = null@@ -121,8 +212,13 @@ async function runQueue() {queueState = 'running'sendFrontendMessage('changedDMQueueInformation', queuedElements, queueState)- const { status } =- element.type === 'install'+ const external = externalDownloads.get(+ updateKey(element.params.appName, element.params.runner)+ )+ if (external) external.claimed = true+ const { status } = external+ ? { status: await external.done }+ : element.type === 'install'? await installQueueElement(element.params): await updateQueueElement(element.params)element.endTime = Date.now()@@ -138,8 +234,10 @@ async function runQueue() {if (!isPaused()) {addToFinished(element, status)removeFromQueue(element.params.appName)+ external?.recorded()element = getFirstQueueElement()} else {+ external?.recorded()element = null}}@@ -335,6 +433,12 @@ function cancelElement(element: DMQueueElement, removeDownloaded: boolean) {removeFromQueue(element.params.appName)const { appName, runner } = element.params+ const external = externalDownloads.get(updateKey(appName, runner))+ if (external) {+ external.cancelled = true+ // Queue loop stops the current one.+ if (!external.claimed) callAbortController(appName)+ }if (runner === 'steam') {// Aurelia knows the safe folder.void forgetSteamInstall(appName, removeDownloaded)@@ -461,6 +565,7 @@ export {cancelCurrentDownload,cancelQueuedDownload,hasFailedUpdate,+ trackExternalDownload,pauseCurrentDownload,resumeCurrentDownload,isRunning,diff --git a/src/backend/storeManagers/steam/__tests__/aurelia.test.ts b/src/backend/storeManagers/steam/__tests__/aurelia.test.tsindex cbbd433ad..2d1de4b57 100644--- a/src/backend/storeManagers/steam/__tests__/aurelia.test.ts+++ b/src/backend/storeManagers/steam/__tests__/aurelia.test.ts@@ -1,7 +1,17 @@-import { AureliaError, parseAureliaJson } from '../aurelia'+import {+ AureliaError,+ aureliaPinsPlatform,+ makeAureliaPlatformInstallHandler,+ parseAureliaJson+} from '../aurelia'+import { callRunner } from 'backend/launcher'+import { getAureliaBin } from 'backend/utils'import type { ExecResult } from 'common/types'jest.mock('backend/launcher', () => ({ callRunner: jest.fn() }))+jest.mock('child_process', () => ({+ spawn: jest.fn(() => ({ on: jest.fn(), unref: jest.fn() }))+}))jest.mock('backend/utils', () => ({getAureliaBin: jest.fn(() => ({ dir: '', bin: 'aurelia' })),getFileSize: jest.fn(),@@ -82,3 +92,41 @@ describe('parseAureliaJson', () => {expect(error.aborted).toBe(true)})})++describe('makeAureliaPlatformInstallHandler', () => {+ it('reports platform installs and ignores other output', () => {+ const events: unknown[] = []+ const handler = makeAureliaPlatformInstallHandler((event) =>+ events.push(event)+ )+ handler(+ [+ '{"event":"message","message":"installing"}',+ '{"event":"platform_install","state":"started","app_id":427520,"platform":"linux"}',+ '{"event":"progress","percent":50}',+ 'not json',+ '{"event":"platform_install","state":"finished","app_id":427520,"platform":"linux"}',+ '{"event":"platform_install","state":"odd","platform":"linux"}'+ ].join('\n')+ )+ expect(events).toEqual([+ { state: 'started', platform: 'linux' },+ { state: 'finished', platform: 'linux' }+ ])+ })+})++describe('aureliaPinsPlatform', () => {+ const run = callRunner as jest.MockedFunction<typeof callRunner>++ it('asks again after a failed read, then caches', async () => {+ jest.mocked(getAureliaBin).mockReturnValue({ dir: '', bin: 'aurelia' })+ run.mockResolvedValueOnce(exec('', 'daemon not ready'))+ expect(await aureliaPinsPlatform()).toBe(false)++ run.mockResolvedValueOnce(exec('{"features":["play.pinned_platform"]}'))+ expect(await aureliaPinsPlatform()).toBe(true)+ expect(await aureliaPinsPlatform()).toBe(true)+ expect(run).toHaveBeenCalledTimes(2)+ })+})diff --git a/src/backend/storeManagers/steam/__tests__/utils.test.ts b/src/backend/storeManagers/steam/__tests__/utils.test.tsindex b95e26d64..96eca67d2 100644--- a/src/backend/storeManagers/steam/__tests__/utils.test.ts+++ b/src/backend/storeManagers/steam/__tests__/utils.test.ts@@ -2,7 +2,9 @@ import { AureliaError } from '../aurelia'import {isDuplicateInstallError,isSteamRunningError,- reportSteamRunning+ pickLaunchTarget,+ reportSteamRunning,+ withoutPlatformFlag} from '../utils'import { showDialogBoxModalAuto } from 'backend/dialog/dialog'@@ -73,6 +75,46 @@ describe('reportSteamRunning', () => {})})+describe('withoutPlatformFlag', () => {+ it('drops the flag and its value', () => {+ expect(+ withoutPlatformFlag(['--platform', 'windows', '--steam-mode', 'host'])+ ).toEqual(['--steam-mode', 'host'])+ expect(withoutPlatformFlag(['--platform', 'linux'])).toEqual([])+ })++ it('leaves other flags alone', () => {+ expect(withoutPlatformFlag(['--steam'])).toEqual(['--steam'])+ })+})++describe('pickLaunchTarget', () => {+ const targets = [+ { id: 'linux', available: true, missing: null },+ { id: 'windows-host', available: false, missing: 'build' },+ { id: 'windows-runtime', available: false, missing: 'steam-runtime' }+ ]++ it('returns an available pick', () => {+ expect(pickLaunchTarget(targets, 'linux', false)?.id).toBe('linux')+ })++ it('keeps a pick whose build is missing only when Aurelia installs it', () => {+ expect(pickLaunchTarget(targets, 'windows-host', false)).toBeUndefined()+ expect(pickLaunchTarget(targets, 'windows-host', true)?.id).toBe(+ 'windows-host'+ )+ })++ it('never keeps a pick missing its Steam runtime', () => {+ expect(pickLaunchTarget(targets, 'windows-runtime', true)).toBeUndefined()+ })++ it('returns nothing without a pick', () => {+ expect(pickLaunchTarget(targets, undefined, true)).toBeUndefined()+ })+})+describe('isSteamSupported', () => {const load = async (env: { isMac: boolean; isFlatpak: boolean }) => {let mod: typeof import('../utils') | undefineddiff --git a/src/backend/storeManagers/steam/aurelia.ts b/src/backend/storeManagers/steam/aurelia.tsindex 086409c38..88319cca2 100644--- a/src/backend/storeManagers/steam/aurelia.ts+++ b/src/backend/storeManagers/steam/aurelia.ts@@ -417,6 +417,43 @@ export function makeAureliaProgressHandler(}}+/** `platform_install` event of `aurelia play --json`. */+interface AureliaPlatformInstallEvent {+ state: 'started' | 'finished' | 'failed'+ platform: string+}++/**+ * Builds an `onOutput` handler reporting the game version Aurelia installs+ * before a launch, when Steam had swapped it for the other platform's.+ */+export function makeAureliaPlatformInstallHandler(+ onEvent: (event: AureliaPlatformInstallEvent) => void+): (data: string) => void {+ return (data: string) => {+ for (const rawLine of stripAnsi(data).split('\n')) {+ const line = rawLine.trim()+ if (!line.startsWith('{')) continue++ let evt: { event?: string; state?: string; platform?: string }+ try {+ evt = JSON.parse(line)+ } catch {+ continue+ }+ if (evt.event !== 'platform_install') continue+ if (+ (evt.state === 'started' ||+ evt.state === 'finished' ||+ evt.state === 'failed') &&+ typeof evt.platform === 'string'+ ) {+ onEvent({ state: evt.state, platform: evt.platform })+ }+ }+ }+}+export function makeAureliaQrHandler(onUrl: (url: string) => void,onScanned?: () => void@@ -508,6 +545,33 @@ export async function aureliaSupportsLaunchOption(): Promise<boolean> {}}+/** Feature name for the enforced per-game platform. */+const PINNED_PLATFORM_FEATURE = 'play.pinned_platform'+// Per binary; failed reads are retried+let pinSupport: { stamp: string; value: Promise<boolean> } | undefined++/**+ * Does `play` enforce `config game --platform`, reinstalling a build Steam+ * swapped away? Cached per Aurelia binary: asked for every launch option+ * list. A failed read is not cached, so the next call asks again.+ */+export async function aureliaPinsPlatform(): Promise<boolean> {+ const stamp = aureliaBinaryStamp()+ if (pinSupport?.stamp === stamp) return pinSupport.value+ const value = runAurelia<AureliaCapabilitiesResponse>(['capabilities']).then(+ ({ features }) => (features ?? []).includes(PINNED_PLATFORM_FEATURE)+ )+ const entry = { stamp, value }+ pinSupport = entry+ try {+ return await value+ } catch (error) {+ if (pinSupport === entry) pinSupport = undefined+ logWarning(['Unable to read Aurelia capabilities', error], LogPrefix.Steam)+ return false+ }+}+/** Outcome of turning Aurelia's sync off. */type AureliaCloudSyncOff = 'off' | 'game-override' | 'unsupported'@@ -586,6 +650,26 @@ export async function setSteamDownloadLimit(kbit: number): Promise<number> {return result.download_limit_kbit ?? 0}+/** When Aurelia downloads a game version the user switched to. */+type SteamPlatformSwitchInstall = 'play' | 'switch'++export async function getSteamPlatformSwitchInstall(): Promise<SteamPlatformSwitchInstall> {+ const result = await runAurelia<{+ platform_switch_install: SteamPlatformSwitchInstall+ }>(['config', 'platform-switch-install'])+ return result.platform_switch_install+}++export async function setSteamPlatformSwitchInstall(+ mode: SteamPlatformSwitchInstall+): Promise<SteamPlatformSwitchInstall> {+ const result = await runAurelia<{+ platform_switch_install: SteamPlatformSwitchInstall+ }>(['config', 'platform-switch-install', mode])+ logInfo(['Steam platform switch install set to', mode], LogPrefix.Steam)+ return result.platform_switch_install+}+/*** Lists the Steam library folders*/diff --git a/src/backend/storeManagers/steam/aurelia_types.ts b/src/backend/storeManagers/steam/aurelia_types.tsindex 0d031cc0a..8c7048b90 100644--- a/src/backend/storeManagers/steam/aurelia_types.ts+++ b/src/backend/storeManagers/steam/aurelia_types.ts@@ -191,6 +191,8 @@ export interface AureliaLinuxRuntimeEvent {/** Result of `aurelia capabilities <command> --json`. */export interface AureliaCapabilitiesResponse {flags?: Array<{ long: string }>+ // Behaviours, listed by the root command only+ features?: string[]}/** One entry from `aurelia launch-targets <id> --json`. */diff --git a/src/backend/storeManagers/steam/games.ts b/src/backend/storeManagers/steam/games.tsindex 6bbefe0e1..4a3d7d047 100644--- a/src/backend/storeManagers/steam/games.ts+++ b/src/backend/storeManagers/steam/games.ts@@ -13,7 +13,8 @@ import {LaunchOption,MoveUnify,Status,- CloudSyncResult+ CloudSyncResult,+ DMStatus} from 'common/types'import { sendProgressUpdate } from 'backend/utils'import {@@ -48,12 +49,15 @@ import {recordCloudSyncResult} from './cloud_sync_status'import {+ aureliaPinsPlatform,+ getSteamPlatformSwitchInstall,aureliaSupportsLaunchOption,disableAureliaCloudSync,runAurelia,fetchAureliaInfo,parseAureliaJson,makeAureliaProgressHandler,+ makeAureliaPlatformInstallHandler,AureliaError} from './aurelia'import { applySteamLinuxRuntime } from './linux_runtime'@@ -66,7 +70,9 @@ import {STEAM_UNSUPPORTED,isSteamRunningError,reportSteamRunning,- steamRunningMessage+ steamRunningMessage,+ pickLaunchTarget,+ withoutPlatformFlag} from './utils'import { buildReqs, stripSteamMarkup, toInstallPlatforms } from './store_info'import { fetchSteamScreenshots } from './store_screenshots'@@ -214,7 +220,8 @@ export default class SteamGame implements Game {missing: target.missing,isDefault: target.default})),- selected: configStore.get('steamLaunchTarget', {})[this.id]+ selected: configStore.get('steamLaunchTarget', {})[this.id],+ pinsPlatform: isLinux && (await aureliaPinsPlatform())}} catch (error) {logWarning(@@ -243,6 +250,21 @@ export default class SteamGame implements Game {configStore.set('steamLaunchTarget', map)}+ /**+ * The game settings closed with a new pick: with `platform-switch-install+ * switch`, hand it to Aurelia now so the download starts before the next+ * launch.+ */+ applyLaunchTarget(): void {+ const targetId = configStore.get('steamLaunchTarget', {})[this.id] ?? ''+ this.pinPlatformOnSwitch(targetId).catch((error: unknown) =>+ logError(+ [`Platform switch failed for ${this.id}`, describeError(error)],+ LogPrefix.Steam+ )+ )+ }+/*** The chosen target if still installed, else Aurelia's default. Undefined when* Aurelia can't list targets (e.g. an older binary).@@ -261,7 +283,7 @@ export default class SteamGame implements Game {return undefined}const selected = configStore.get('steamLaunchTarget', {})[this.id]- const chosen = this.chosenLaunchTarget(targets)+ const chosen = await this.chosenLaunchTarget(targets)if (selected && !chosen) {await logWriter.logWarning(`Launch target ${selected} is not available, using the default`@@ -270,11 +292,125 @@ export default class SteamGame implements Game {return chosen ?? targets.find((target) => target.default)}- private chosenLaunchTarget(+ private async chosenLaunchTarget(targets: AureliaLaunchTarget[]- ): AureliaLaunchTarget | undefined {+ ): Promise<AureliaLaunchTarget | undefined> {+ const selected = configStore.get('steamLaunchTarget', {})[this.id]+ if (!selected) return undefined+ return pickLaunchTarget(+ targets,+ selected,+ isLinux && (await aureliaPinsPlatform())+ )+ }++ /**+ * Set or clear the game's enforced platform in Aurelia. With Aurelia's+ * `platform-switch-install switch` this downloads the picked version right+ * away, shown in the download manager. Returns the failure text, if any;+ * `aborted` when the user cancelled it.+ */+ private async setPinnedPlatform(+ pinned: 'linux' | 'windows' | undefined,+ logWriter?: LogWriter+ ): Promise<{ failure?: string; aborted?: boolean }> {+ const platformInstall = this.platformInstallTracker(+ this.getGameInfo(),+ // During a launch the game starts afterwards+ logWriter ? 'playing' : undefined,+ logWriter+ )+ const res = await libraryManagerMap['steam'].runRunnerCommand(+ [+ 'config',+ 'game',+ this.id,+ ...(pinned ? ['--platform', pinned] : ['--no-platform']),+ '--json'+ ],+ {+ abortId: this.id,+ fullOutput: true,+ logWriters: logWriter ? [logWriter] : [],+ onOutput: platformInstall.onOutput+ }+ )+ await platformInstall.settle()+ try {+ // Non-zero exits resolve too+ parseAureliaJson(res)+ return {}+ } catch (error) {+ const failure = describeError(error)+ const aborted = error instanceof AureliaError && error.aborted+ logWarning(+ [`Could not set the platform for ${this.id}`, failure],+ LogPrefix.Steam+ )+ return { failure, aborted }+ }+ }++ private async pinPlatformOnSwitch(targetId: string): Promise<void> {+ if (!isLinux || !(await aureliaPinsPlatform())) return+ try {+ if ((await getSteamPlatformSwitchInstall()) !== 'switch') return+ } catch (error) {+ logWarning(+ ['Unable to read the platform switch setting', describeError(error)],+ LogPrefix.Steam+ )+ return+ }+ const pinned = targetId.startsWith('linux')+ ? 'linux'+ : targetId.startsWith('windows')+ ? 'windows'+ : undefined+ const { failure, aborted } = await this.setPinnedPlatform(pinned)+ if (failure && !aborted) {+ showDialogBoxModalAuto({+ title: t(+ 'box.error.steam-platform-switch.title',+ 'Could not switch the game version'+ ),+ message: failure,+ type: 'ERROR'+ })+ }+ try {+ await libraryManagerMap['steam'].refresh()+ sendFrontendMessage('refreshLibrary', 'steam')+ } catch (error) {+ logWarning(+ [`Failed to refresh Steam library for ${this.id}`, error],+ LogPrefix.Steam+ )+ }+ }++ /**+ * Hand the picked platform to Aurelia as the game's enforced platform, so+ * Play runs only that build and Aurelia reinstalls it after Steam swapped+ * it. Returns the `play` flags for the target.+ */+ private async applyPlatformPin(+ target: AureliaLaunchTarget,+ logWriter: LogWriter+ ): Promise<string[]> {+ if (!isLinux || !(await aureliaPinsPlatform())) return target.flagsconst selected = configStore.get('steamLaunchTarget', {})[this.id]- return targets.find((target) => target.id === selected && target.available)+ // Automatic: Aurelia picks, nothing enforced+ const pinned = selected === target.id ? target.platform : undefined+ const { failure } = await this.setPinnedPlatform(pinned, logWriter)+ if (failure) {+ await logWriter.logWarning(`Platform not enforced: ${failure}`)+ return target.flags+ }+ if (!pinned) return target.flags+ await logWriter.logInfo(`Enforced platform: ${pinned}`)+ // An explicit --platform would override the enforced one+ return withoutPlatformFlag(target.flags)}/**@@ -285,7 +421,7 @@ export default class SteamGame implements Game {try {const targets = await this.fetchLaunchTargets()const target =- this.chosenLaunchTarget(targets) ??+ (await this.chosenLaunchTarget(targets)) ??targets.find((value) => value.default)return target?.platform ?? installed} catch (error) {@@ -297,6 +433,94 @@ export default class SteamGame implements Game {}}+ /**+ * Shows the game version Aurelia downloads while starting the game in the+ * download manager: current download with progress, then history. Call+ * `settle` when `play` ends, in case it stopped mid-download.+ */+ private platformInstallTracker(+ gameInfo: GameInfo,+ // Status once the download is done, if the game goes on to start+ statusAfter: 'playing' | undefined,+ logWriter?: LogWriter+ ): { onOutput: (data: string) => void; settle: () => Promise<void> } {+ type Finish = ((status: DMStatus) => Promise<void>) | undefined+ // Pending until the queue module loads+ let tracking: Promise<Finish> | undefined+ // Set once the queue shows it+ let tracked = false+ const forwardProgress = makeAureliaProgressHandler(this.id, 'installing')++ const end = async (status: DMStatus): Promise<boolean> => {+ const pending = tracking+ tracking = undefined+ tracked = false+ const finish = await pending+ if (!finish) return false+ await finish(status)+ return true+ }++ const onInstallEvent = makeAureliaPlatformInstallHandler(+ ({ state, platform }) => {+ if (state === 'started') {+ void logWriter?.logInfo(+ `Aurelia is installing the ${platform} version`+ )+ const now = Date.now()+ // Lazy: queue imports store managers+ tracking = import('backend/downloadmanager/downloadqueue').then(+ ({ trackExternalDownload }) => {+ const finish = trackExternalDownload({+ type: 'install',+ params: {+ appName: this.id,+ runner: 'steam',+ gameInfo,+ path: gameInfo.install.install_path ?? '',+ platformToInstall: platform === 'linux' ? 'linux' : 'Windows'+ },+ addToQueueTime: now,+ startTime: now,+ endTime: 0+ })+ if (finish) {+ tracked = true+ sendGameStatusUpdate({+ appName: this.id,+ runner: 'steam',+ status: 'installing'+ })+ }+ return finish+ }+ )+ return+ }+ void end(state === 'finished' ? 'done' : 'error').then((wasTracked) => {+ // Queue said done; game starts now+ if (wasTracked && state === 'finished' && statusAfter) {+ sendGameStatusUpdate({+ appName: this.id,+ runner: 'steam',+ status: statusAfter+ })+ }+ })+ }+ )++ return {+ onOutput: (data: string) => {+ onInstallEvent(data)+ if (tracked) forwardProgress(data)+ },+ settle: async () => {+ await end('abort')+ }+ }+ }+/*** Usable `--launch-option` id for Play.*/@@ -1191,7 +1415,7 @@ export default class SteamGame implements Game {if (target) {// Target flags pick build and Steam modeawait logWriter.logInfo(`Launch target: ${target.id}`)- playCommand.push(...target.flags)+ playCommand.push(...(await this.applyPlatformPin(target, logWriter)))if (isLinux && target.platform === 'windows') {await pushProton()}@@ -1211,10 +1435,17 @@ export default class SteamGame implements Game {playCommand.push('--launch-option', launchOptionId)}+ const platformInstall = this.platformInstallTracker(+ gameInfo,+ 'playing',+ logWriter+ )const res = await libraryManagerMap['steam'].runRunnerCommand(playCommand, {abortId: this.id,- logWriters: [logWriter]+ logWriters: [logWriter],+ onOutput: platformInstall.onOutput})+ await platformInstall.settle()launchCleanup(prep.rpcClient)diff --git a/src/backend/storeManagers/steam/ipc_handler.ts b/src/backend/storeManagers/steam/ipc_handler.tsindex 354f89161..345a45610 100644--- a/src/backend/storeManagers/steam/ipc_handler.ts+++ b/src/backend/storeManagers/steam/ipc_handler.ts@@ -3,8 +3,10 @@ import { SteamUser } from './user'import { libraryManagerMap } from '..'import {getSteamDownloadLimit,+ getSteamPlatformSwitchInstall,runAurelia,- setSteamDownloadLimit+ setSteamDownloadLimit,+ setSteamPlatformSwitchInstall} from './aurelia'import { describeError } from './utils'import {@@ -14,6 +16,7 @@ import {setSteamLinuxRuntime} from './linux_runtime'import { logError, LogPrefix } from 'backend/logger'+import { isLinux } from 'backend/constants/environment'addHandler('getSteamUsers', () => SteamUser.getAccounts())@@ -31,6 +34,32 @@ addHandler('setSteamDownloadLimit', async (_e, kbit) =>setSteamDownloadLimit(kbit))+// Only Linux has two versions to switch between+addHandler('getSteamPlatformSwitchInstall', async () => {+ if (!isLinux) return undefined+ try {+ return await getSteamPlatformSwitchInstall()+ } catch (error) {+ logError(+ ['Unable to read the platform switch setting', describeError(error)],+ LogPrefix.Steam+ )+ return undefined+ }+})++addHandler('setSteamPlatformSwitchInstall', async (_e, mode) => {+ try {+ return await setSteamPlatformSwitchInstall(mode)+ } catch (error) {+ logError(+ ['Unable to set the platform switch setting', describeError(error)],+ LogPrefix.Steam+ )+ throw error+ }+})+addHandler('getSteamCloudSyncStatus', (_e, appName) =>libraryManagerMap['steam'].getGame(appName).getCloudSyncStatus())@@ -76,6 +105,10 @@ addHandler('setSteamLaunchTarget', (_e, appName, targetId) =>libraryManagerMap['steam'].getGame(appName).setLaunchTarget(targetId))+addHandler('applySteamLaunchTarget', (_e, appName) =>+ libraryManagerMap['steam'].getGame(appName).applyLaunchTarget()+)+// Opens the Windows Steam installer under WineaddHandler('installSteamWineRuntime', async () => {try {diff --git a/src/backend/storeManagers/steam/utils.ts b/src/backend/storeManagers/steam/utils.tsindex f6a74b1ee..0bc6b1751 100644--- a/src/backend/storeManagers/steam/utils.ts+++ b/src/backend/storeManagers/steam/utils.ts@@ -158,3 +158,32 @@ export async function steamCall<T>(return fallback}}++/** A launch target's `play` flags without `--platform <value>`. */+export function withoutPlatformFlag(flags: string[]): string[] {+ const at = flags.indexOf('--platform')+ if (at < 0) return flags+ return [...flags.slice(0, at), ...flags.slice(at + 2)]+}++interface SelectableTarget {+ id: string+ available: boolean+ missing: string | null+}++/**+ * The user's pick, if Play can use it. With an enforced platform, Aurelia+ * downloads a missing build itself, so that pick stays valid.+ */+export function pickLaunchTarget<T extends SelectableTarget>(+ targets: T[],+ selected: string | undefined,+ pinsPlatform: boolean+): T | undefined {+ return targets.find(+ (target) =>+ target.id === selected &&+ (target.available || (pinsPlatform && target.missing === 'build'))+ )+}diff --git a/src/common/types/ipc.ts b/src/common/types/ipc.tsindex a8217bf8e..b7825af6b 100644--- a/src/common/types/ipc.ts+++ b/src/common/types/ipc.ts@@ -278,6 +278,10 @@ interface AsyncIPCFunctions {getSteamInstallLibraries: () => Promise<SteamInstallLibrary[]>getSteamDownloadLimit: () => Promise<number>setSteamDownloadLimit: (kbit: number) => Promise<number>+ getSteamPlatformSwitchInstall: () => Promise<'play' | 'switch' | undefined>+ setSteamPlatformSwitchInstall: (+ mode: 'play' | 'switch'+ ) => Promise<'play' | 'switch'>focusGameWindow: () => Promise<void>setSteamDlcEnabled: (dlcAppId: string, enabled: boolean) => Promise<void>getSteamLinuxRuntimeSettings: () => Promise<SteamLinuxRuntimeSettings>@@ -292,6 +296,7 @@ interface AsyncIPCFunctions {) => Promise<SteamLinuxRuntimeGame>getSteamLaunchTargets: (appName: string) => Promise<SteamLaunchTargets>setSteamLaunchTarget: (appName: string, targetId: string) => void+ applySteamLaunchTarget: (appName: string) => voidinstallSteamWineRuntime: () => Promise<{status: 'done' | 'error'error?: stringdiff --git a/src/common/types/steam.ts b/src/common/types/steam.tsindex 564c74f49..093c0e1c9 100644--- a/src/common/types/steam.ts+++ b/src/common/types/steam.ts@@ -45,6 +45,8 @@ export interface SteamLaunchTargets {targets: SteamLaunchTarget[]// User's chosen target idselected?: string+ // Play downloads a missing pick+ pinsPlatform?: boolean}export interface SteamInstallLibrary {diff --git a/src/frontend/hooks/useLaunchOptions.ts b/src/frontend/hooks/useLaunchOptions.tsindex 89d8375ef..c8e4c3dbb 100644--- a/src/frontend/hooks/useLaunchOptions.ts+++ b/src/frontend/hooks/useLaunchOptions.ts@@ -21,6 +21,18 @@ export const useLaunchOptions = ({const { t } = useTranslation('gamepage')const [launchOptions, setLaunchOptions] = useState<LaunchOption[]>([])const [selectedIndex, setSelectedIndex] = useState(-1)+ const [reloads, setReloads] = useState(0)++ // A Steam game's options depend on the version picked to launch+ useEffect(() => {+ const onTargetChanged = (event: CustomEvent<{ appName: string }>) => {+ if (event.detail.appName === appName) setReloads((count) => count + 1)+ }+ window.addEventListener('steam-launch-target-changed', onTargetChanged)+ return () => {+ window.removeEventListener('steam-launch-target-changed', onTargetChanged)+ }+ }, [appName])// Fetch launch optionsuseEffect(() => {@@ -40,7 +52,7 @@ export const useLaunchOptions = ({if (appName && runner) {void fetchOptions()}- }, [appName, runner, isInstalled])+ }, [appName, runner, isInstalled, reloads])// Find and set the previously used optionuseMemo(() => {diff --git a/src/frontend/hooks/useSteamLaunchTargets.ts b/src/frontend/hooks/useSteamLaunchTargets.tsindex 8adbb2e11..7873260b4 100644--- a/src/frontend/hooks/useSteamLaunchTargets.ts+++ b/src/frontend/hooks/useSteamLaunchTargets.ts@@ -1,4 +1,4 @@-import { useCallback, useEffect, useState } from 'react'+import { useCallback, useEffect, useRef, useState } from 'react'import type { GameInfo } from 'common/types'import type { SteamLaunchTarget } from 'common/types/steam'@@ -12,6 +12,8 @@ export interface SteamLaunchTargetsState {effective?: SteamLaunchTarget// Launch platform, known offline tooplatform?: string+ // Missing picks download on their own+ pinsPlatform: boolean}/**@@ -24,6 +26,10 @@ export function useSteamLaunchTargets(): SteamLaunchTargetsState {const [targets, setTargets] = useState<SteamLaunchTarget[]>([])const [selected, setSelected] = useState('')+ const [pinsPlatform, setPinsPlatform] = useState(false)+ // Pick when settings opened+ const initial = useRef<string>()+ const latest = useRef<string>()const active =enabled && gameInfo?.runner === 'steam' && !!gameInfo.is_installed@@ -37,16 +43,35 @@ export function useSteamLaunchTargets(const result = await window.api.getSteamLaunchTargets(appName)setTargets(result.targets)setSelected(result.selected ?? '')+ initial.current ??= result.selected ?? ''+ latest.current ??= result.selected ?? ''+ setPinsPlatform(result.pinsPlatform ?? false)}, [appName, active])useEffect(() => {void refresh()}, [refresh, installPath])+ // Changed pick applies on settings close+ useEffect(() => {+ initial.current = undefined+ latest.current = undefined+ return () => {+ if (latest.current !== initial.current) {+ void window.api.applySteamLaunchTarget(appName)+ }+ }+ }, [appName])+const select = useCallback(async (targetId: string) => {setSelected(targetId)+ latest.current = targetIdawait window.api.setSteamLaunchTarget(appName, targetId)+ // Launch options follow the platform+ window.dispatchEvent(+ new CustomEvent('steam-launch-target-changed', { detail: { appName } })+ )},[appName])@@ -62,7 +87,15 @@ export function useSteamLaunchTargets(String(gameInfo?.install?.platform ?? '').toLowerCase()): undefined- return { targets, selected, select, refresh, effective, platform }+ return {+ targets,+ selected,+ select,+ refresh,+ effective,+ platform,+ pinsPlatform+ }}/** Platform encoded in a target id. */diff --git a/src/frontend/screens/Settings/components/SteamLaunchTarget.tsx b/src/frontend/screens/Settings/components/SteamLaunchTarget.tsxindex e865a4bf7..6b79889eb 100644--- a/src/frontend/screens/Settings/components/SteamLaunchTarget.tsx+++ b/src/frontend/screens/Settings/components/SteamLaunchTarget.tsx@@ -1,4 +1,4 @@-import { useContext, useState } from 'react'+import { useContext, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import { MenuItem, SelectChangeEvent } from '@mui/material'import DownIcon from 'frontend/assets/down-icon.svg?react'@@ -21,10 +21,18 @@ interface Props {const SteamLaunchTarget = ({ state }: Props) => {const { t } = useTranslation()const { appName, isDefault, gameInfo } = useContext(SettingsContext)- const { targets, selected, select, refresh } = state+ const { targets, selected, select, refresh, pinsPlatform } = stateconst [busy, setBusy] = useState(false)const [error, setError] = useState('')+ const [downloadsOnSwitch, setDownloadsOnSwitch] = useState(false)++ useEffect(() => {+ void window.api+ .getSteamPlatformSwitchInstall()+ .then((mode) => setDownloadsOnSwitch(mode === 'switch'))+ .catch(() => setDownloadsOnSwitch(false))+ }, [])const installPath = gameInfo?.install?.install_path@@ -112,8 +120,16 @@ const SteamLaunchTarget = ({ state }: Props) => {}}+ // Only one platform's files stay installed+ const switchesPlatform =+ new Set(targets.map((target) => target.platform)).size > 1++ // Pinned builds download on switch/play+ const downloadsItself = pinsPlatform && current?.missing === 'build'+const canDownload =- current?.missing === 'build' || current?.missing === 'steam-runtime'+ (current?.missing === 'build' && !downloadsItself) ||+ current?.missing === 'steam-runtime'return (<SelectField@@ -159,13 +175,26 @@ const SteamLaunchTarget = ({ state }: Props) => {)}</button>)}- {current && !current.available && fallback && (+ {current && !current.available && !downloadsItself && fallback && (<span className="smallInputInfo steamLaunchTarget__label">{t('setting.steamLaunchTarget.fallback', 'Until then, Play uses')}{labelFor(fallback)}</span>)}{error && <span className="smallInputInfo danger">{error}</span>}+ {switchesPlatform && (+ <span className="smallInputInfo">+ {downloadsOnSwitch+ ? t(+ 'setting.steamLaunchTarget.platformSwitchNoteNow',+ 'Switching platform downloads it when you close the settings.'+ )+ : t(+ 'setting.steamLaunchTarget.platformSwitchNote',+ 'Switching platform downloads it on next launch.'+ )}+ </span>+ )}</>}>diff --git a/src/frontend/screens/Settings/components/SteamPlatformSwitchInstall.tsx b/src/frontend/screens/Settings/components/SteamPlatformSwitchInstall.tsxnew file mode 100644index 000000000..384c3e0c2--- /dev/null+++ b/src/frontend/screens/Settings/components/SteamPlatformSwitchInstall.tsx@@ -0,0 +1,56 @@+import { useEffect, useState } from 'react'+import { ToggleSwitch } from 'frontend/components/UI'+import { useTranslation } from 'react-i18next'++/**+ * Aurelia setting: download a Steam game's other version when it is picked,+ * or only on the next launch.+ */+const SteamPlatformSwitchInstall = () => {+ const { t } = useTranslation()+ const [mode, setMode] = useState<'play' | 'switch'>()+ const [busy, setBusy] = useState(false)++ useEffect(() => {+ void window.api.getSteamPlatformSwitchInstall().then(setMode)+ }, [])++ // Not on Linux, or unreadable+ if (!mode) {+ return <></>+ }++ const toggle = async () => {+ // One call at a time+ if (busy) return+ const next = mode === 'switch' ? 'play' : 'switch'+ setBusy(true)+ setMode(next)+ try {+ setMode(await window.api.setSteamPlatformSwitchInstall(next))+ } catch {+ setMode(mode)+ } finally {+ setBusy(false)+ }+ }++ return (+ <ToggleSwitch+ description={t(+ 'setting.steamPlatformSwitchInstall-description',+ 'Start the download when you close the game settings after picking the Linux or Windows version of a Steam game, instead of on its next launch'+ )}+ htmlId="steamPlatformSwitchInstall"+ value={mode === 'switch'}+ disabled={busy}+ handleChange={() => void toggle()}+ title={t(+ 'setting.steamPlatformSwitchInstall',+ 'Download Steam game versions when switching'+ )}+ />+ )+}++export default SteamPlatformSwitchInstalldiff --git a/src/frontend/screens/Settings/components/index.ts b/src/frontend/screens/Settings/components/index.tsindex 133f8081d..4af0174d0 100644--- a/src/frontend/screens/Settings/components/index.ts+++ b/src/frontend/screens/Settings/components/index.ts@@ -13,6 +13,7 @@ export { default as AutoUpdateGames } from './AutoUpdateGames'export { default as AutoVKD3D } from './AutoVKD3D'export { default as BattlEyeRuntime } from './BattlEyeRuntime'export { default as CheckUpdatesOnStartup } from './CheckUpdatesOnStartup'+export { default as SteamPlatformSwitchInstall } from './SteamPlatformSwitchInstall'export { default as CrossoverBottle } from './CrossoverBottle'export { default as CustomWineProton } from './CustomWineProton'export { default as CustomCSS } from './CustomCSS'diff --git a/src/frontend/screens/Settings/sections/GeneralSettings/index.tsx b/src/frontend/screens/Settings/sections/GeneralSettings/index.tsxindex c5d833290..c4b0d915a 100644--- a/src/frontend/screens/Settings/sections/GeneralSettings/index.tsx+++ b/src/frontend/screens/Settings/sections/GeneralSettings/index.tsx@@ -30,7 +30,8 @@ import {WinePrefixesBasePath,PlaytimeSync,AnalyticsOptIn,- BackupSaves+ BackupSaves,+ SteamPlatformSwitchInstall} from '../../components'export default function GeneralSettings() {@@ -70,6 +71,7 @@ export default function GeneralSettings() {<AutoUpdateGames /><CheckUpdatesOnStartup /><MaxWorkers />+ <SteamPlatformSwitchInstall /><DownloadUnits /></SettingsCard>diff --git a/src/frontend/types.ts b/src/frontend/types.tsindex f77267b4c..41c9a033a 100644--- a/src/frontend/types.ts+++ b/src/frontend/types.ts@@ -221,6 +221,7 @@ declare global {interface WindowEventMap {'visible-cards': CustomEvent<{ appNames: string[] }>'controller-changed': CustomEvent<{ controllerId: string }>+ 'steam-launch-target-changed': CustomEvent<{ appName: string }>}}diff --git a/src/preload/api/steam.ts b/src/preload/api/steam.tsindex 904911a06..088f4d8fd 100644--- a/src/preload/api/steam.ts+++ b/src/preload/api/steam.ts@@ -5,6 +5,8 @@ export const getSteamDlcInfo = makeHandlerInvoker('getSteamDlcInfo')export const getSteamInstallLibraries = makeHandlerInvoker('getSteamInstallLibraries')export const getSteamDownloadLimit = makeHandlerInvoker('getSteamDownloadLimit')export const setSteamDownloadLimit = makeHandlerInvoker('setSteamDownloadLimit')+export const getSteamPlatformSwitchInstall = makeHandlerInvoker('getSteamPlatformSwitchInstall')+export const setSteamPlatformSwitchInstall = makeHandlerInvoker('setSteamPlatformSwitchInstall')export const setSteamDlcEnabled = makeHandlerInvoker('setSteamDlcEnabled')export const getSteamLinuxRuntimeSettings = makeHandlerInvoker('getSteamLinuxRuntimeSettings')export const setSteamLinuxRuntimeSetting = makeHandlerInvoker('setSteamLinuxRuntimeSetting')@@ -12,6 +14,7 @@ export const getSteamLinuxRuntime = makeHandlerInvoker('getSteamLinuxRuntime')export const setSteamLinuxRuntime = makeHandlerInvoker('setSteamLinuxRuntime')export const getSteamLaunchTargets = makeHandlerInvoker('getSteamLaunchTargets')export const setSteamLaunchTarget = makeHandlerInvoker('setSteamLaunchTarget')+export const applySteamLaunchTarget = makeHandlerInvoker('applySteamLaunchTarget')export const installSteamWineRuntime = makeHandlerInvoker('installSteamWineRuntime')export const loginSteam = makeHandlerInvoker('loginSteam')export const loginSteamQr = makeHandlerInvoker('loginSteamQr')