diff --git a/apps/launcher/electron.vite.config.ts b/apps/launcher/electron.vite.config.ts index 6ab858d..341bbdc 100644 --- a/apps/launcher/electron.vite.config.ts +++ b/apps/launcher/electron.vite.config.ts @@ -15,6 +15,7 @@ export default defineConfig({ input: { index: resolve('src/main/index.ts'), 'build-worker': resolve('src/main/workers/build-worker.ts'), + 'server-worker': resolve('src/main/workers/server-worker.ts'), 'save-worker': resolve('src/main/workers/save-worker.ts'), 'patch-check-worker': resolve('src/main/workers/patch-check-worker.ts'), }, diff --git a/apps/launcher/src/main/services/config/settings-store.ts b/apps/launcher/src/main/services/config/settings-store.ts index c7c2bf0..0cdfef2 100644 --- a/apps/launcher/src/main/services/config/settings-store.ts +++ b/apps/launcher/src/main/services/config/settings-store.ts @@ -11,6 +11,7 @@ import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts'; */ let cached: Settings | null = null; +let pending: Promise = Promise.resolve(); function settingsPath(): string { return join(app.getPath('userData'), 'settings.json'); @@ -35,17 +36,21 @@ export async function getSettings(): Promise { return cached; } -export async function updateSettings(patch: SettingsPatch): Promise { - const current = await getSettings(); - const merged = SettingsSchema.parse({ ...current, ...definedFields(patch) }); - try { - await writeJsonAtomic(settingsPath(), merged); - } catch (error) { - console.error('[settings] write failed:', error); - throw new AppError('settings_write_failed'); - } - cached = merged; - return merged; +export function updateSettings(patch: SettingsPatch): Promise { + const operation = pending.then(async () => { + const current = await getSettings(); + const merged = SettingsSchema.parse({ ...current, ...definedFields(patch) }); + try { + await writeJsonAtomic(settingsPath(), merged); + } catch (error) { + console.error('[settings] write failed:', error); + throw new AppError('settings_write_failed'); + } + cached = merged; + return merged; + }); + pending = operation.then(() => undefined, () => undefined); + return operation; } /** The patch without the fields it leaves out, so they do not overwrite current values. */ diff --git a/apps/launcher/src/main/services/copies/copy-maintenance.ts b/apps/launcher/src/main/services/copies/copy-maintenance.ts index 5c0ff6a..1395821 100644 --- a/apps/launcher/src/main/services/copies/copy-maintenance.ts +++ b/apps/launcher/src/main/services/copies/copy-maintenance.ts @@ -15,7 +15,8 @@ import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, upda import { checkPatches } from '../install/patch-check.ts'; import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts'; import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts'; -import { labStatusUrl, readInstalledLab } from '../launch/lab-handoff.ts'; +import { readInstalledLab } from '../launch/lab-handoff.ts'; +import { localServerReady } from '../launch/local-server.ts'; import { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts'; let current: { stop: AbortController; interruptible: boolean } | null = null; @@ -130,12 +131,7 @@ async function safeFolder(path: string): Promise { async function labServerUses(root: string): Promise { const lab = await readInstalledLab().catch(() => null); if (!lab || relative(lab.copyPath, root) !== '') return false; - try { - const response = await fetch(labStatusUrl(lab.port), { signal: AbortSignal.timeout(800) }); - return response.ok && (await response.json() as { app?: string }).app === 'wto-server'; - } catch { - return false; - } + return localServerReady(lab.port); } async function recordCheck(record: InstallRecord, folder: string): Promise { diff --git a/apps/launcher/src/main/services/launch/game-process.ts b/apps/launcher/src/main/services/launch/game-process.ts new file mode 100644 index 0000000..6540d55 --- /dev/null +++ b/apps/launcher/src/main/services/launch/game-process.ts @@ -0,0 +1,50 @@ +import { execFile, spawn } from 'node:child_process'; +import { join } from 'node:path'; +import { promisify } from 'node:util'; +import { GAME_FILES } from '@wto/patcher'; +import { AppError } from '@shared/errors.ts'; +import { ORDINARY_LAUNCH_ENABLED } from '@shared/schemas/launch.ts'; + +const execute = promisify(execFile); +const OFFLINE_ARGUMENTS = ['-forcestart', '-nobeac', '-crashpad-disable-upload']; + +export async function gameProcessRunning(signal: AbortSignal): Promise { + if (process.platform !== 'win32') return false; + const games = await execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal }); + return /^"aces\.exe",/im.test(games.stdout); +} + +export async function runGameProcess( + copyPath: string, additionalArguments: readonly string[], signal: AbortSignal, onStart: () => void, +): Promise { + if (!ORDINARY_LAUNCH_ENABLED || process.platform !== 'win32') throw new AppError('launch_disabled'); + if (await gameProcessRunning(signal)) throw new AppError('launch_game_running'); + signal.throwIfAborted(); + const child = spawn(join(copyPath, GAME_FILES.executable), [...OFFLINE_ARGUMENTS, ...additionalArguments], { + cwd: copyPath, shell: false, stdio: 'ignore', + }); + const stop = (): void => { child.kill(); }; + + try { + await new Promise((resolve, reject) => { + child.once('spawn', () => { + if (signal.aborted) stop(); + else onStart(); + }); + child.once('error', (error) => { + console.error('[game] process error:', error); + reject(new AppError('launch_game_failed')); + }); + child.once('close', (code, reason) => { + if (code === 0 || signal.aborted) resolve(); + else { + console.error('[game] process exited:', code ?? reason); + reject(new AppError('launch_game_failed')); + } + }); + signal.addEventListener('abort', stop, { once: true }); + }); + } finally { + signal.removeEventListener('abort', stop); + } +} diff --git a/apps/launcher/src/main/services/launch/lab-handoff.ts b/apps/launcher/src/main/services/launch/lab-handoff.ts index c693b17..b52185d 100644 --- a/apps/launcher/src/main/services/launch/lab-handoff.ts +++ b/apps/launcher/src/main/services/launch/lab-handoff.ts @@ -3,8 +3,8 @@ import { lstat, readFile, realpath, writeFile } from 'node:fs/promises'; import { isAbsolute, join, relative, resolve } from 'node:path'; import { app } from 'electron'; import { z } from 'zod'; -import { HEALTH_PATH } from '@wto/server'; import { AppError } from '@shared/errors.ts'; +import { localServerReady } from './local-server.ts'; import { forwardProcessOutput } from './process-output.ts'; const Configuration = z.object({ @@ -18,7 +18,6 @@ const Status = z.object({ message: z.string(), guardExitCode: z.number().nullable().optional(), }); -const Health = z.object({ app: z.literal('wto-server'), pid: z.number() }); export interface Lab { readonly installPath: string; @@ -58,10 +57,6 @@ export async function readInstalledLab(): Promise { } } -export function labStatusUrl(port: number): string { - return `http://127.0.0.1:${port}${HEALTH_PATH}`; -} - async function readStatus(lab: Lab): Promise | null> { try { return Status.parse(JSON.parse(await readFile(join(lab.controlPath, 'status.json'), 'utf8'))); @@ -70,15 +65,6 @@ async function readStatus(lab: Lab): Promise | null> { } } -async function isReady(port: number, pid: number): Promise { - try { - const response = await fetch(labStatusUrl(port), { signal: AbortSignal.timeout(900) }); - return response.ok && Health.parse(await response.json()).pid === pid; - } catch { - return false; - } -} - async function stopGame(lab: Lab): Promise { await writeFile(join(lab.controlPath, 'stop-request'), '', { flag: 'wx' }).catch((error: NodeJS.ErrnoException) => { if (error.code !== 'EEXIST') throw error; @@ -145,7 +131,7 @@ export async function runLab( return; } checking = true; - void isReady(lab.port, serverPid).then((ready) => { + void localServerReady(lab.port, serverPid).then((ready) => { if (!running || processClosed) return; failures = ready ? 0 : failures + 1; if (failures < 3) return; diff --git a/apps/launcher/src/main/services/launch/launch-controller.ts b/apps/launcher/src/main/services/launch/launch-controller.ts index e71497d..5f6d1d1 100644 --- a/apps/launcher/src/main/services/launch/launch-controller.ts +++ b/apps/launcher/src/main/services/launch/launch-controller.ts @@ -1,21 +1,22 @@ -import { execFile } from 'node:child_process'; import { readFile } from 'node:fs/promises'; import { createServer } from 'node:net'; -import { isAbsolute, join, relative } from 'node:path'; -import { promisify } from 'node:util'; -import { BrowserWindow, shell } from 'electron'; -import { AccountStore } from '@wto/server'; +import { isAbsolute, join } from 'node:path'; +import { app, BrowserWindow, shell } from 'electron'; +import { AccountStore, LOOPBACK } from '@wto/server'; import { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; -import type { LaunchState } from '@shared/schemas/launch.ts'; +import { ORDINARY_LAUNCH_ENABLED, type LaunchState } from '@shared/schemas/launch.ts'; import { getSettings } from '../config/settings-store.ts'; -import { readInstallRecord } from '../install/install-record.ts'; +import { copyPathContains, readInstallRecord } from '../install/install-record.ts'; import { resourcePaths } from '../resources/resource-paths.ts'; import { saveBackup } from '../saves/save-archive.ts'; import { buildCopy } from './build-copy.ts'; -import { labStatusUrl, readInstalledLab, runLab } from './lab-handoff.ts'; +import { gameProcessRunning } from './game-process.ts'; +import { readInstalledLab, runLab } from './lab-handoff.ts'; +import { localServerStatusUrl } from './local-server.ts'; +import { ordinaryLaunchPaths, runOrdinaryLaunch } from './ordinary-launch.ts'; -const execute = promisify(execFile); +export { gameProcessRunning } from './game-process.ts'; interface LaunchJob { readonly stop: AbortController; @@ -31,30 +32,31 @@ export function launchInProgress(): boolean { return active !== null; } -export async function gameProcessRunning(signal: AbortSignal): Promise { - if (process.platform !== 'win32') return false; - const games = await execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal }); - return /^"aces\.exe",/im.test(games.stdout); -} - export function getLaunchState(): LaunchState { return state; } export function startLaunch(report: LaunchJob['report']): LaunchState { - if (active) throw new AppError('launch_busy'); + const previous = active; + if (previous && state.phase !== 'server-running') throw new AppError('launch_busy'); const job: LaunchJob = { stop: new AbortController(), report, done: Promise.resolve() }; active = job; + previous?.stop.abort(); update(job, { phase: 'checking' }); - job.done = launch(job).catch((error: unknown) => { - const port = state.port; - const context = port === undefined ? {} : { port }; + job.done = (async () => { + // A new build may only write after the server from the previous session has stopped. + await previous?.done; + job.stop.signal.throwIfAborted(); + await launch(job); + })().catch((error: unknown) => { if (job.stop.signal.aborted) { update(job, { phase: 'ready' }); return; } + const { port } = state; + const context = port === undefined ? {} : { port }; console.error('[launch] launch failed:', error); - const code = error instanceof AppError ? error.code : 'launch_lab_failed'; + const code = error instanceof AppError ? error.code : 'launch_failed'; switch (code) { case 'launch_port_busy': update(job, { phase: 'port-busy', ...context }); @@ -67,7 +69,7 @@ export function startLaunch(report: LaunchJob['report']): LaunchState { break; } }).finally(() => { - active = null; + if (active === job) active = null; }); return state; } @@ -83,11 +85,14 @@ export function stopLaunch(): Promise | null { } export async function openServerStatus(): Promise { - if (state.phase !== 'running' || state.port === undefined) throw new AppError('launch_server_exited'); - await shell.openExternal(labStatusUrl(state.port)); + if ((state.phase !== 'running' && state.phase !== 'server-running') || state.port === undefined) { + throw new AppError('launch_server_exited'); + } + await shell.openExternal(localServerStatusUrl(state.port)); } function update(job: LaunchJob, next: LaunchState): void { + if (active !== job) return; state = job.copyId ? { ...next, copyId: job.copyId } : next; job.report(state); } @@ -97,7 +102,10 @@ async function launch(job: LaunchJob): Promise { const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]); if (!record) throw new AppError('launch_no_copy'); job.copyId = record.id; - if (!settings.developerMode) throw new AppError('launch_lab_required'); + const useLab = !app.isPackaged && settings.developerMode; + if (!useLab && !ORDINARY_LAUNCH_ENABLED) { + throw new AppError(app.isPackaged ? 'launch_disabled' : 'launch_lab_required'); + } if (isInSteamLibrary(record.copyPath)) throw new AppError('launch_copy_in_steam'); const currentVersion = await readVersion(record.copyPath, signal); if (!currentVersion || currentVersion !== record.gameVersion) { @@ -105,26 +113,31 @@ async function launch(job: LaunchJob): Promise { return; } - const lab = await readInstalledLab(); - const stockPath = settings.labStockPath ?? record.stockBackupPath; - const dataPath = settings.labDataPath ?? record.dataPath; + const lab = useLab ? await readInstalledLab() : null; + const { copyPath, stockPath, dataPath } = lab ? { + copyPath: lab.copyPath, + stockPath: settings.labStockPath ?? record.stockBackupPath, + dataPath: settings.labDataPath ?? record.dataPath, + } : await ordinaryLaunchPaths(record); if (!isAbsolute(stockPath) || !isAbsolute(dataPath)) { throw new AppError('folder_unreadable', { path: !isAbsolute(stockPath) ? stockPath : dataPath }); } - const relativeData = relative(stockPath, dataPath); - if (isInSteamLibrary(dataPath) || (!isAbsolute(relativeData) && !relativeData.startsWith('..'))) { + if (isInSteamLibrary(dataPath) || copyPathContains(stockPath, dataPath)) { throw new AppError('launch_copy_in_steam'); } - update(job, { phase: 'checking', port: lab.port }); - const [labVersion, stockVersion, games] = await Promise.all([ - readVersion(lab.copyPath, signal), + const requestedPort = lab?.port ?? (settings.launchPortMode === 'fixed' ? settings.launchPort : 0); + if (requestedPort) update(job, { phase: 'checking', port: requestedPort }); + const [copyVersion, stockVersion, games] = await Promise.all([ + lab ? readVersion(copyPath, signal) : currentVersion, readVersion(stockPath, signal), gameProcessRunning(signal), ]); signal.throwIfAborted(); - if (!labVersion || labVersion !== stockVersion) throw new AppError('launch_lab_version'); + if (!copyVersion || copyVersion !== stockVersion) { + throw new AppError(lab ? 'launch_lab_version' : 'launch_stock_version'); + } if (games) throw new AppError('launch_game_running'); - await checkPort(lab.port); + const port = await selectPort(requestedPort); if (settings.autoSaveBackups) { for (const { userId } of new AccountStore(dataPath).all()) { signal.throwIfAborted(); @@ -132,27 +145,30 @@ async function launch(job: LaunchJob): Promise { } } signal.throwIfAborted(); - update(job, { phase: 'building', port: lab.port }); + update(job, { phase: 'building', port }); await buildCopy({ kind: 'build', stockPath, - copyPath: lab.copyPath, + copyPath, dataPath, - port: lab.port, + port, ...resourcePaths(), acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId), }, signal, (filesWritten, filesTotal, file) => { if (!signal.aborted) update(job, { - phase: 'building', port: lab.port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }), + phase: 'building', port, filesWritten, filesTotal, ...(file === undefined ? {} : { file }), }); }); - await runLab(lab, stockPath, dataPath, signal, (phase) => { - if (!signal.aborted) update(job, { phase, port: lab.port }); - if (phase === 'running' && !signal.aborted && settings.afterGameStarts === 'minimize') { + const publish = (phase: LaunchState['phase']): void => { + if (signal.aborted) return; + update(job, { phase, port }); + if (phase === 'running' && settings.afterGameStarts === 'minimize') { for (const window of BrowserWindow.getAllWindows()) window.minimize(); } - }); + }; + if (lab) await runLab(lab, stockPath, dataPath, signal, publish); + else await runOrdinaryLaunch(copyPath, dataPath, port, settings, signal, publish); update(job, { phase: 'ready' }); } @@ -166,12 +182,19 @@ async function readVersion(folder: string, signal: AbortSignal): Promise { - await new Promise((resolve, reject) => { +async function selectPort(port: number): Promise { + return new Promise((resolve, reject) => { const listener = createServer(); listener.once('error', (error: NodeJS.ErrnoException) => reject( error.code === 'EADDRINUSE' ? new AppError('launch_port_busy') : error, )); - listener.listen(port, '127.0.0.1', () => listener.close((error) => error ? reject(error) : resolve())); + listener.listen(port, LOOPBACK, () => { + const address = listener.address(); + listener.close((error) => { + if (error) reject(error); + else if (address && typeof address === 'object') resolve(address.port); + else reject(new AppError('launch_server_failed')); + }); + }); }); } diff --git a/apps/launcher/src/main/services/launch/local-server.ts b/apps/launcher/src/main/services/launch/local-server.ts new file mode 100644 index 0000000..022c897 --- /dev/null +++ b/apps/launcher/src/main/services/launch/local-server.ts @@ -0,0 +1,92 @@ +import { once } from 'node:events'; +import { join } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { utilityProcess } from 'electron'; +import { z } from 'zod'; +import { HEALTH_PATH, LOOPBACK, type ServerOptions } from '@wto/server'; +import { AppError } from '@shared/errors.ts'; +import type { ServerWorkerStatus } from '../../workers/server-worker.ts'; +import { forwardProcessOutput } from './process-output.ts'; + +const Health = z.object({ app: z.literal('wto-server'), pid: z.number() }); + +interface LocalServer { + readonly exited: Promise; + close(): Promise; +} + +export function localServerStatusUrl(port: number): string { + return `http://${LOOPBACK}:${port}${HEALTH_PATH}`; +} + +export async function localServerReady(port: number, pid?: number, signal?: AbortSignal): Promise { + const deadline = AbortSignal.timeout(900); + try { + const response = await fetch(localServerStatusUrl(port), { + redirect: 'error', signal: signal ? AbortSignal.any([signal, deadline]) : deadline, + }); + if (!response.ok) return false; + const health = Health.parse(await response.json()); + return pid === undefined || health.pid === pid; + } catch { + return false; + } +} + +export async function startLocalServer( + { gameFolder, dataFolder, port }: Omit, signal: AbortSignal, +): Promise { + signal.throwIfAborted(); + const worker = utilityProcess.fork(join(import.meta.dirname, 'server-worker.js'), [gameFolder, dataFolder, String(port)], { + serviceName: 'WTOffline local server', + stdio: 'pipe', + }); + forwardProcessOutput(worker.stdout, 'server', 'info'); + forwardProcessOutput(worker.stderr, 'server', 'error'); + + let ended = false; + const exited = new Promise((resolve) => worker.once('exit', (code) => { + ended = true; + resolve(code); + })); + worker.on('error', (type, location) => console.error('[server] utility process error:', type, location)); + + const stop = async (graceful: boolean): Promise => { + if (!ended && graceful) { + worker.postMessage('close'); + await Promise.race([exited, delay(3000, undefined, { ref: false })]); + } + if (!ended && !worker.kill() && worker.pid === undefined) { + worker.once('spawn', () => worker.kill()); + } + await exited; + }; + + const startup = AbortSignal.any([signal, AbortSignal.timeout(60_000)]); + let listening = false; + try { + const reply: ServerWorkerStatus = await Promise.race([ + once(worker, 'message', { signal: startup }).then(([status]) => status as ServerWorkerStatus), + exited.then(() => 'failed' as const), + ]); + if (reply === 'port-busy') throw new AppError('launch_port_busy'); + const pid = worker.pid; + if (reply !== 'listening' || pid === undefined) throw new AppError('launch_server_failed'); + listening = true; + while (!ended) { + startup.throwIfAborted(); + if (await localServerReady(port, pid, startup)) { + startup.throwIfAborted(); + if (!ended) return { exited, close: () => stop(true) }; + break; + } + await delay(150, undefined, { signal: startup }); + } + throw new AppError('launch_server_failed'); + } catch (error) { + await stop(listening); + signal.throwIfAborted(); + console.error('[server] startup failed:', error); + throw error instanceof AppError ? error : new AppError('launch_server_failed'); + } +} diff --git a/apps/launcher/src/main/services/launch/ordinary-launch.ts b/apps/launcher/src/main/services/launch/ordinary-launch.ts new file mode 100644 index 0000000..254831a --- /dev/null +++ b/apps/launcher/src/main/services/launch/ordinary-launch.ts @@ -0,0 +1,60 @@ +import { once } from 'node:events'; +import { isAbsolute, join, relative } from 'node:path'; +import { GAME_FILES, isInSteamLibrary } from '@wto/patcher'; +import { AppError } from '@shared/errors.ts'; +import { parseLaunchArguments } from '@shared/launch-arguments.ts'; +import { ORDINARY_LAUNCH_ENABLED } from '@shared/schemas/launch.ts'; +import type { InstallRecord } from '@shared/schemas/install.ts'; +import type { Settings } from '@shared/schemas/settings.ts'; +import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts'; +import { STOCK_BACKUP_FOLDER } from '../install/stock-backup.ts'; +import { runGameProcess } from './game-process.ts'; +import { startLocalServer } from './local-server.ts'; + +export async function ordinaryLaunchPaths(record: InstallRecord) { + const paths = [record.copyPath, record.stockBackupPath, record.dataPath] as const; + if (paths.some((path) => !isAbsolute(path))) throw new AppError('launch_location'); + const [copyPath, stockPath, dataPath] = await Promise.all([ + canonicalCopyPath(record.copyPath), canonicalCopyPath(record.stockBackupPath), canonicalCopyPath(record.dataPath), + ]); + const executable = await canonicalCopyPath(join(copyPath, GAME_FILES.executable)); + const source = record.sourcePath; + if (relative(copyPath, stockPath).toLowerCase() !== STOCK_BACKUP_FOLDER.toLowerCase() || + relative(copyPath, executable).toLowerCase() !== GAME_FILES.executable.toLowerCase() || + copyPathContains(stockPath, dataPath) || + (source !== null && [copyPath, dataPath].some((path) => copyPathContains(source, path)))) { + throw new AppError('launch_location'); + } + if (isInSteamLibrary(copyPath) || isInSteamLibrary(dataPath)) throw new AppError('launch_copy_in_steam'); + return { copyPath: copyPath, stockPath: stockPath, dataPath: dataPath }; +} + +type OrdinaryPhase = 'starting-server' | 'starting-game' | 'running' | 'server-running'; + +export async function runOrdinaryLaunch( + copyPath: string, dataPath: string, port: number, settings: Settings, signal: AbortSignal, + publish: (phase: OrdinaryPhase) => void, +): Promise { + if (!ORDINARY_LAUNCH_ENABLED) throw new AppError('launch_disabled'); + const args = parseLaunchArguments(settings.launchArguments); + if (!args) throw new AppError('launch_game_failed'); + publish('starting-server'); + const server = await startLocalServer({ gameFolder: copyPath, dataFolder: dataPath, port }, signal); + const stop = new AbortController(); + const runSignal = AbortSignal.any([signal, stop.signal]); + const serverExited = server.exited.then(() => { throw new AppError('launch_server_exited'); }); + publish('starting-game'); + const game = runGameProcess(copyPath, args, runSignal, () => publish('running')); + try { + await Promise.race([game, serverExited]); + runSignal.throwIfAborted(); + if (!settings.closeServerOnGameExit) { + publish('server-running'); + if (!runSignal.aborted) await Promise.race([once(runSignal, 'abort'), serverExited]); + } + } finally { + stop.abort(); + await game.catch(() => undefined); + await server.close(); + } +} diff --git a/apps/launcher/src/main/services/saves/manage-saves.ts b/apps/launcher/src/main/services/saves/manage-saves.ts index 01bba30..7354946 100644 --- a/apps/launcher/src/main/services/saves/manage-saves.ts +++ b/apps/launcher/src/main/services/saves/manage-saves.ts @@ -8,7 +8,8 @@ import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protoco import { maintenanceInProgress } from '../copies/copy-maintenance.ts'; import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts'; import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts'; -import { labStatusUrl, readInstalledLab } from '../launch/lab-handoff.ts'; +import { readInstalledLab } from '../launch/lab-handoff.ts'; +import { localServerReady } from '../launch/local-server.ts'; import { forwardProcessOutput } from '../launch/process-output.ts'; import { archivedBackup, backupList, captureSave, changeSaveFolder, readArchive, restoreDirectory, saveBackup, writeArchive, type SaveArchive } from './save-archive.ts'; @@ -267,12 +268,7 @@ async function write(operation: () => Promise): Promise { async function labServerRunning(): Promise { const lab = await readInstalledLab().catch(() => null); if (!lab) return false; - try { - const response = await fetch(labStatusUrl(lab.port), { signal: AbortSignal.timeout(600) }); - return response.ok && (await response.json() as { app?: string }).app === 'wto-server'; - } catch { - return false; - } + return localServerReady(lab.port); } async function run(task: SaveTask): Promise { diff --git a/apps/launcher/src/main/workers/server-worker.ts b/apps/launcher/src/main/workers/server-worker.ts new file mode 100644 index 0000000..e8b3b60 --- /dev/null +++ b/apps/launcher/src/main/workers/server-worker.ts @@ -0,0 +1,29 @@ +import { startServer } from '@wto/server'; + +export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed'; + +async function serve(): Promise { + const [gameFolder, dataFolder, portText] = process.argv.slice(2); + const port = Number(portText); + if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error('Invalid local server arguments.'); + } + const server = await startServer({ gameFolder, dataFolder, port, report: console.info }); + console.info('Traffic log:', server.logFolder); + process.parentPort.once('message', () => { + void server.close().then(() => process.exit(0)).catch((error: unknown) => { + console.error('Could not close the local server:', error); + process.exit(1); + }); + }); + send('listening'); +} + +function send(status: ServerWorkerStatus): void { + process.parentPort.postMessage(status); +} + +void serve().catch((error: unknown) => { + console.error('Could not start the local server:', error); + send((error as NodeJS.ErrnoException).code === 'EADDRINUSE' ? 'port-busy' : 'failed'); +}); diff --git a/apps/launcher/src/renderer/src/App.tsx b/apps/launcher/src/renderer/src/App.tsx index 212a6b5..2e9c231 100644 --- a/apps/launcher/src/renderer/src/App.tsx +++ b/apps/launcher/src/renderer/src/App.tsx @@ -2,7 +2,7 @@ import { useEffect, useState, type ReactNode } from 'react'; import { useTranslation } from 'react-i18next'; import type { IpcOutput } from '@shared/ipc/contract.ts'; import type { Copies } from '@shared/schemas/install.ts'; -import type { LaunchState } from '@shared/schemas/launch.ts'; +import { ORDINARY_LAUNCH_ENABLED, type LaunchState } from '@shared/schemas/launch.ts'; import type { Settings } from '@shared/schemas/settings.ts'; import { Sheet } from './components/Sheet.tsx'; import { applyLanguage, resolveLanguage } from './i18n/index.ts'; @@ -96,6 +96,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) { const perCopyStatus = ['version-changed', 'failed', 'port-busy', 'server-exited'].includes(launch.phase); const launchStatus: LaunchState = perCopyStatus && launch.copyId && launch.copyId !== record?.id ? { phase: 'ready' } : launch; const home = homeBar(record, launchStatus, t, wizard.start, { + canStart: ORDINARY_LAUNCH_ENABLED || (info.development && settings.developerMode), start: () => { ipcInvoke('launch:start').catch(report); }, stop: () => { ipcInvoke('launch:stop').catch(report); }, checkVersion: () => go({ page: 'copies', section: 'features' }), @@ -124,8 +125,8 @@ export function App({ info, initialSettings, initialCopies }: AppProps) { const sections = SETTINGS_SECTIONS.filter((section) => info.development || section !== 'dev'); const content = { general: , - launch: , - diag: , + launch: , + diag: , dev: , }; return { @@ -138,7 +139,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) { return { side: t(`saves.sections.${section}`)} onSelect={(section) => go({ page: 'saves', section })} />, main: record - ? + ? :

{t('saves.noCopy')}

, bar: home, }; diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index ee0b73d..a2acef2 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -76,7 +76,9 @@ "starting": "Starting…", "running": "Game running", "runningDetail": "Local server · Port {{port}}", - "stopping": "Stopping game", + "server-running": "Local server running", + "stopping": "Stopping", + "stopServer": "Close local server", "cancel": "Cancel", "stop": "End game", "retry": "Retry", @@ -442,7 +444,13 @@ "portHint": "Port set by the installed lab automation", "exit": "When the game exits", "exitHint": "Isolated launch", - "automatic": "Close local server" + "automatic": "Close local server", + "portMode": "Port assignment", + "autoPort": "Assign automatically", + "fixedPort": "Specify port", + "arguments": "Additional arguments", + "argumentsHint": "Command-line arguments passed to the game", + "argumentsInvalid": "Close each double quote in the launch arguments." }, "developer": { "mode": "Developer mode", @@ -597,16 +605,22 @@ "maintenance_source_changed": "The installation source changed during the update. Retry once its update is complete.", "launch_no_copy": "A game copy must be installed before launching.", "launch_busy": "A launch is already in progress.", + "launch_failed": "Launch failed. See the launcher log.", + "launch_disabled": "Standard launch is pending isolation verification.", "launch_lab_required": "Enable developer mode to launch through the isolated lab.", "launch_lab_missing": "The isolated lab automation could not be loaded.", "launch_lab_version": "The lab copy and the stock backup must use the same game version.", "launch_lab_failed": "The isolated launch failed. See the launcher log.", "launch_game_running": "Another game process is running.", "launch_copy_in_steam": "The launch requires a separate copy and data folder outside Steam.", + "launch_location": "The game copy, stock backup, or data folder location is invalid.", + "launch_stock_version": "The stock backup and game copy versions do not match.", "launch_build_failed": "The game files could not be generated.", "launch_build_unavailable": "The build found unavailable patches that require review.", "launch_port_busy": "The local server port is already in use.", + "launch_server_failed": "The local server could not be started. See the launcher log.", "launch_server_exited": "The local server is unavailable.", + "launch_game_failed": "The game process failed to start or exited unexpectedly. See the launcher log.", "settings_write_failed": "The settings could not be saved.", "folder_unreadable": "The folder cannot be read: {{path}}", "not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index 2f37dd8..c7e9877 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -76,7 +76,9 @@ "starting": "启动中…", "running": "游戏运行中", "runningDetail": "本地服务器 · 端口 {{port}}", - "stopping": "正在结束游戏", + "server-running": "本地服务器运行中", + "stopping": "正在关闭", + "stopServer": "关闭本地服务器", "cancel": "取消", "stop": "结束游戏", "retry": "重试", @@ -442,7 +444,13 @@ "portHint": "使用已安装实验自动化的端口设置", "exit": "游戏退出后", "exitHint": "隔离启动", - "automatic": "关闭本地服务器" + "automatic": "关闭本地服务器", + "portMode": "端口分配方式", + "autoPort": "自动分配", + "fixedPort": "指定端口", + "arguments": "附加启动参数", + "argumentsHint": "传递给游戏的命令行参数", + "argumentsInvalid": "请补全启动参数中的双引号。" }, "developer": { "mode": "开发模式", @@ -597,16 +605,22 @@ "maintenance_source_changed": "安装来源在更新过程中发生变化。请在正版更新完成后重试。", "launch_no_copy": "启动前需要安装游戏副本。", "launch_busy": "启动流程正在运行。", + "launch_failed": "启动失败。请查看启动器日志。", + "launch_disabled": "普通启动待隔离验收。", "launch_lab_required": "请启用开发模式以通过隔离实验副本启动。", "launch_lab_missing": "无法读取隔离实验自动化配置。", "launch_lab_version": "实验副本和原版文件备份必须使用同一游戏版本。", "launch_lab_failed": "隔离启动失败。请查看启动器日志。", "launch_game_running": "已有游戏进程在运行。", "launch_copy_in_steam": "启动需使用 Steam 目录外的副本和数据目录。", + "launch_location": "副本、原版文件备份或数据目录的位置无效。", + "launch_stock_version": "原版文件备份的版本与副本不一致。", "launch_build_failed": "无法生成游戏文件。", "launch_build_unavailable": "生成游戏文件时发现需要重新确认的不可用补丁。", "launch_port_busy": "本地服务器端口已被占用。", + "launch_server_failed": "无法启动本地服务器。请查看启动器日志。", "launch_server_exited": "本地服务器不可用。", + "launch_game_failed": "游戏进程启动失败或意外退出。请查看启动器日志。", "settings_write_failed": "无法保存设置。", "folder_unreadable": "无法读取文件夹:{{path}}", "not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}", diff --git a/apps/launcher/src/renderer/src/pages/home/home-bar.ts b/apps/launcher/src/renderer/src/pages/home/home-bar.ts index 21bab4a..8213b94 100644 --- a/apps/launcher/src/renderer/src/pages/home/home-bar.ts +++ b/apps/launcher/src/renderer/src/pages/home/home-bar.ts @@ -5,6 +5,7 @@ import type { BarModel } from '../../shell/bar-model.ts'; import { missingFeatures } from '../copies/missing-features.ts'; interface LaunchActions { + readonly canStart: boolean; readonly start: () => void; readonly stop: () => void; readonly checkVersion: () => void; @@ -18,8 +19,8 @@ export function homeBar( onInstall: () => void, actions: LaunchActions, ): BarModel { - const launch = { label: t('bar.launch'), onClick: actions.start }; - const retry = { label: t('launch.retry'), onClick: actions.start }; + const launch = { label: t('bar.launch'), onClick: actions.start, disabled: !actions.canStart }; + const retry = { label: t('launch.retry'), onClick: actions.start, disabled: !actions.canStart }; const starting = { label: t('launch.starting'), disabled: true }; const progress = { value: state.filesWritten ?? 0, max: state.filesTotal || null }; switch (state.phase) { @@ -41,6 +42,7 @@ export function homeBar( title: t(`launch.${state.phase}`), progress: { value: 0, max: null }, primary: starting, + ...(state.phase === 'stopping' ? {} : { secondary: { label: t('launch.cancel'), onClick: actions.stop } }), }; case 'running': return { @@ -50,6 +52,14 @@ export function homeBar( primary: { label: t('launch.running'), disabled: true }, secondary: { label: t('launch.stop'), onClick: actions.stop }, }; + case 'server-running': + return { + tone: 'ok', + title: t('launch.server-running'), + detail: t('launch.runningDetail', { port: state.port }), + primary: launch, + secondary: { label: t('launch.stopServer'), onClick: actions.stop }, + }; case 'port-busy': return { tone: 'bad', title: t('launch.port-busy', { port: state.port }), primary: retry }; case 'server-exited': @@ -62,7 +72,7 @@ export function homeBar( primary: { label: t('launch.check'), onClick: actions.checkVersion }, }; case 'failed': - return { tone: 'bad', title: t(`errors.${state.error ?? 'launch_lab_failed'}`), primary: retry }; + return { tone: 'bad', title: t(`errors.${state.error ?? 'launch_failed'}`), primary: retry }; case 'ready': break; } @@ -75,6 +85,9 @@ export function homeBar( primary: { label: t('bar.install'), onClick: onInstall }, }; } + if (!actions.canStart) { + return { tone: 'warn', title: t('errors.launch_disabled'), primary: launch }; + } const missing = missingFeatures(record).length; return { tone: missing ? 'warn' : 'ok', diff --git a/apps/launcher/src/renderer/src/pages/settings/LaunchSettings.tsx b/apps/launcher/src/renderer/src/pages/settings/LaunchSettings.tsx index c47d65c..e9b2d49 100644 --- a/apps/launcher/src/renderer/src/pages/settings/LaunchSettings.tsx +++ b/apps/launcher/src/renderer/src/pages/settings/LaunchSettings.tsx @@ -1,28 +1,104 @@ import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; import type { IpcOutput } from '@shared/ipc/contract.ts'; +import { parseLaunchArguments } from '@shared/launch-arguments.ts'; +import { ORDINARY_LAUNCH_ENABLED } from '@shared/schemas/launch.ts'; +import { LAUNCH_ARGUMENTS_LIMIT, type Settings, type SettingsPatch } from '@shared/schemas/settings.ts'; import { Row } from '../../components/Row.tsx'; import { Sheet } from '../../components/Sheet.tsx'; import { ipcInvoke } from '../../ipc.ts'; -export function LaunchSettings({ onError }: { readonly onError: (error: unknown) => void }) { +interface LaunchSettingsProps { + readonly settings: Settings; + readonly development: boolean; + readonly onError: (error: unknown) => void; +} + +export function LaunchSettings({ settings, development, onError }: LaunchSettingsProps) { const { t } = useTranslation(); const [lab, setLab] = useState>(null); + const useLab = development && settings.developerMode; useEffect(() => { + if (!useLab) return; let mounted = true; ipcInvoke('launch:getLabInfo').then((info) => { if (mounted) setLab(info); }).catch(onError); return () => { mounted = false; }; - }, [onError]); + }, [onError, useLab]); + + const update = (patch: SettingsPatch): void => { ipcInvoke('settings:update', patch).catch(onError); }; + const title = t('settings.sections.launch'); + if (useLab) { + return ( + + {lab?.port ?? '—'} + {t('settings.launch.automatic')} + + ); + } + if (!ORDINARY_LAUNCH_ENABLED) { + return

{t('errors.launch_disabled')}

; + } return ( - - - {lab?.port ?? '—'} + + + + { + const input = event.currentTarget; + if (!input.reportValidity()) return; + if (settings.launchPort !== input.valueAsNumber) update({ launchPort: input.valueAsNumber }); + }} + /> - - {t('settings.launch.automatic')} + + + + + event.currentTarget.setCustomValidity('')} + onBlur={(event) => { + const input = event.currentTarget; + if (!parseLaunchArguments(input.value)) { + input.setCustomValidity(t('settings.launch.argumentsInvalid')); + input.reportValidity(); + return; + } + if (input.value !== settings.launchArguments) update({ launchArguments: input.value }); + }} + /> ); diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index c2dab1a..521c5dd 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -40,16 +40,22 @@ export const APP_ERROR_CODES = [ 'copy_location_in_use', 'launch_no_copy', 'launch_busy', + 'launch_failed', + 'launch_disabled', 'launch_lab_required', 'launch_lab_missing', 'launch_lab_version', 'launch_lab_failed', 'launch_game_running', 'launch_copy_in_steam', + 'launch_location', + 'launch_stock_version', 'launch_build_failed', 'launch_build_unavailable', 'launch_port_busy', + 'launch_server_failed', 'launch_server_exited', + 'launch_game_failed', /** A folder the player chose does not exist or cannot be read (params: path). */ 'folder_unreadable', /** The chosen folder lacks the files of a War Thunder installation (params: path). */ diff --git a/apps/launcher/src/shared/launch-arguments.ts b/apps/launcher/src/shared/launch-arguments.ts new file mode 100644 index 0000000..72a9271 --- /dev/null +++ b/apps/launcher/src/shared/launch-arguments.ts @@ -0,0 +1,39 @@ +/** Split the launch setting into Windows arguments without going through a command shell. */ +export function parseLaunchArguments(text: string): string[] | null { + if (/[\0\r\n]/.test(text)) return null; + const args: string[] = []; + let argument = ''; + let quoted = false; + let started = false; + let backslashes = 0; + + for (const character of text) { + if (character === '\\') { + backslashes++; + started = true; + continue; + } + if (character === '"') { + argument += '\\'.repeat(Math.floor(backslashes / 2)); + if (backslashes % 2 === 1) argument += '"'; + else quoted = !quoted; + backslashes = 0; + started = true; + continue; + } + argument += '\\'.repeat(backslashes); + backslashes = 0; + if (!quoted && (character === ' ' || character === '\t')) { + if (started) args.push(argument); + argument = ''; + started = false; + continue; + } + argument += character; + started = true; + } + + if (quoted) return null; + if (started) args.push(argument + '\\'.repeat(backslashes)); + return args; +} diff --git a/apps/launcher/src/shared/schemas/launch.ts b/apps/launcher/src/shared/schemas/launch.ts index a2280f8..6b8101b 100644 --- a/apps/launcher/src/shared/schemas/launch.ts +++ b/apps/launcher/src/shared/schemas/launch.ts @@ -1,10 +1,13 @@ import { z } from 'zod'; import { APP_ERROR_CODES } from '../errors.ts'; +// Enable only after isolation has been verified and the maintainer approves the change. +export const ORDINARY_LAUNCH_ENABLED = false; + export const LaunchStateSchema = z.object({ phase: z.enum([ 'ready', 'checking', 'building', 'starting-server', 'starting-game', 'running', - 'stopping', 'port-busy', 'version-changed', 'server-exited', 'failed', + 'server-running', 'stopping', 'port-busy', 'version-changed', 'server-exited', 'failed', ]), copyId: z.uuid().optional(), port: z.number().int().min(1).max(65535).optional(), diff --git a/apps/launcher/src/shared/schemas/settings.ts b/apps/launcher/src/shared/schemas/settings.ts index 598ab4e..21c94ea 100644 --- a/apps/launcher/src/shared/schemas/settings.ts +++ b/apps/launcher/src/shared/schemas/settings.ts @@ -1,11 +1,16 @@ import { z } from 'zod'; import { LANGUAGE_CHOICES } from '../languages.ts'; +import { parseLaunchArguments } from '../launch-arguments.ts'; import { BACKGROUND_RANDOM, BackgroundChoiceSchema } from './background.ts'; const LanguageChoiceSchema = z.enum(LANGUAGE_CHOICES); const WindowCloseSchema = z.enum(['quit', 'tray']); const AfterGameStartsSchema = z.enum(['minimize', 'keep']); const LabPathSchema = z.string().min(1).nullable(); +const PortModeSchema = z.enum(['auto', 'fixed']); +const PortSchema = z.number().int().min(1).max(65535); +export const LAUNCH_ARGUMENTS_LIMIT = 4000; +const LaunchArgumentsSchema = z.string().max(LAUNCH_ARGUMENTS_LIMIT).refine((value) => parseLaunchArguments(value) !== null); /** The launcher's own settings (not the game's, not the local service's tuning). */ export const SettingsSchema = z.object({ @@ -19,6 +24,10 @@ export const SettingsSchema = z.object({ windowClose: WindowCloseSchema.default('quit'), afterGameStarts: AfterGameStartsSchema.default('minimize'), autoSaveBackups: z.boolean().default(true), + launchPortMode: PortModeSchema.default('auto'), + launchPort: PortSchema.default(27015), + closeServerOnGameExit: z.boolean().default(true), + launchArguments: LaunchArgumentsSchema.default(''), developerMode: z.boolean().default(true), labStockPath: LabPathSchema.default(null), labDataPath: LabPathSchema.default(null), @@ -35,6 +44,10 @@ export const SettingsPatchSchema = z.object({ windowClose: WindowCloseSchema.optional(), afterGameStarts: AfterGameStartsSchema.optional(), autoSaveBackups: z.boolean().optional(), + launchPortMode: PortModeSchema.optional(), + launchPort: PortSchema.optional(), + closeServerOnGameExit: z.boolean().optional(), + launchArguments: LaunchArgumentsSchema.optional(), developerMode: z.boolean().optional(), labStockPath: LabPathSchema.optional(), labDataPath: LabPathSchema.optional(),