feat(launcher): implement gated standard launch

Build the selected copy for its port, wait for the local server, and manage the game and server lifecycles. Keep standard launch disabled pending isolation verification.

Verified both type checks, the launcher build, and the launch lifecycle against a temporary copy and a stand-in executable.
This commit is contained in:
N0VAN0M4LY committed 2026-11-30 09:40:58 +08:00
1 parent 2a97b0d46c
commit c1dea23955
19 files changed
+522 -105

No files matched your search

+1
View File
@@ -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'),
},
@@ -11,6 +11,7 @@ import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
*/
let cached: Settings | null = null;
let pending: Promise<void> = Promise.resolve();
function settingsPath(): string {
return join(app.getPath('userData'), 'settings.json');
@@ -35,17 +36,21 @@ export async function getSettings(): Promise<Settings> {
return cached;
}
export async function updateSettings(patch: SettingsPatch): Promise<Settings> {
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<Settings> {
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. */
@@ -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<string> {
async function labServerUses(root: string): Promise<boolean> {
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<Copies> {
@@ -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<boolean> {
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<void> {
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<void>((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);
}
}
@@ -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<Lab> {
}
}
export function labStatusUrl(port: number): string {
return `http://127.0.0.1:${port}${HEALTH_PATH}`;
}
async function readStatus(lab: Lab): Promise<z.output<typeof Status> | 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<z.output<typeof Status> | null> {
}
}
async function isReady(port: number, pid: number): Promise<boolean> {
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<void> {
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;
@@ -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<boolean> {
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<void> | null {
}
export async function openServerStatus(): Promise<void> {
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<void> {
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<void> {
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<void> {
}
}
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<string
}
}
async function checkPort(port: number): Promise<void> {
await new Promise<void>((resolve, reject) => {
async function selectPort(port: number): Promise<number> {
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'));
});
});
});
}
@@ -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<number>;
close(): Promise<void>;
}
export function localServerStatusUrl(port: number): string {
return `http://${LOOPBACK}:${port}${HEALTH_PATH}`;
}
export async function localServerReady(port: number, pid?: number, signal?: AbortSignal): Promise<boolean> {
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<ServerOptions, 'report'>, signal: AbortSignal,
): Promise<LocalServer> {
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<number>((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<void> => {
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');
}
}
@@ -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<void> {
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();
}
}
@@ -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<T>(operation: () => Promise<T>): Promise<T> {
async function labServerRunning(): Promise<boolean> {
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<SaveResult> {
@@ -0,0 +1,29 @@
import { startServer } from '@wto/server';
export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed';
async function serve(): Promise<void> {
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');
});
+5 -4
View File
@@ -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: <GeneralSettings settings={settings} pictures={backgrounds.pictures} onError={report} />,
launch: <LaunchSettings onError={report} />,
diag: <DiagnosticsSettings onError={report} serverRunning={launch.phase === 'running'} />,
launch: <LaunchSettings settings={settings} development={info.development} onError={report} />,
diag: <DiagnosticsSettings onError={report} serverRunning={launch.phase === 'running' || launch.phase === 'server-running'} />,
dev: <DeveloperSettings settings={settings} onError={report} />,
};
return {
@@ -138,7 +139,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
return {
side: <SubNav sections={SAVE_SECTIONS} active={route.saves} label={(section) => t(`saves.sections.${section}`)} onSelect={(section) => go({ page: 'saves', section })} />,
main: record
? <SavesPage key={record.id} copy={record} copies={registry.copies} section={route.saves} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'stopping'].includes(launch.phase)} onError={report} />
? <SavesPage key={record.id} copy={record} copies={registry.copies} section={route.saves} readOnly={['checking', 'building', 'starting-server', 'starting-game', 'running', 'server-running', 'stopping'].includes(launch.phase)} onError={report} />
: <Sheet title={t(`saves.sections.${route.saves}`)}><p className="lead">{t('saves.noCopy')}</p></Sheet>,
bar: home,
};
@@ -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}}",
@@ -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}}",
@@ -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',
@@ -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<IpcOutput<'launch:getLabInfo'>>(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 (
<Sheet title={title}>
<Row label={t('settings.launch.port')} hint={t('settings.launch.portHint')}>{lab?.port ?? '—'}</Row>
<Row label={t('settings.launch.exit')} hint={t('settings.launch.exitHint')}>{t('settings.launch.automatic')}</Row>
</Sheet>
);
}
if (!ORDINARY_LAUNCH_ENABLED) {
return <Sheet title={title}><p className="lead">{t('errors.launch_disabled')}</p></Sheet>;
}
return (
<Sheet title={t('settings.sections.launch')}>
<Row label={t('settings.launch.port')} hint={t('settings.launch.portHint')}>
{lab?.port ?? '—'}
<Sheet title={title}>
<Row label={t('settings.launch.port')}>
<select
className="select"
aria-label={t('settings.launch.portMode')}
value={settings.launchPortMode}
onChange={(event) => update({ launchPortMode: event.currentTarget.value === 'fixed' ? 'fixed' : 'auto' })}
>
<option value="auto">{t('settings.launch.autoPort')}</option>
<option value="fixed">{t('settings.launch.fixedPort')}</option>
</select>
<input
className="select"
aria-label={t('settings.launch.port')}
type="number"
min={1}
max={65535}
required
disabled={settings.launchPortMode === 'auto'}
defaultValue={settings.launchPort}
key={settings.launchPort}
onBlur={(event) => {
const input = event.currentTarget;
if (!input.reportValidity()) return;
if (settings.launchPort !== input.valueAsNumber) update({ launchPort: input.valueAsNumber });
}}
/>
</Row>
<Row label={t('settings.launch.exit')} hint={t('settings.launch.exitHint')}>
{t('settings.launch.automatic')}
<Row label={t('settings.launch.exit')}>
<label className="check check-inline">
<input
type="checkbox"
checked={settings.closeServerOnGameExit}
onChange={(event) => update({ closeServerOnGameExit: event.currentTarget.checked })}
/>
{t('settings.launch.automatic')}
</label>
</Row>
<Row label={t('settings.launch.arguments')} hint={t('settings.launch.argumentsHint')}>
<input
className="select"
aria-label={t('settings.launch.arguments')}
placeholder="-windowed"
maxLength={LAUNCH_ARGUMENTS_LIMIT}
defaultValue={settings.launchArguments}
key={settings.launchArguments}
onChange={(event) => 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 });
}}
/>
</Row>
</Sheet>
);
+6
View File
@@ -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). */
@@ -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;
}
+4 -1
View File
@@ -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(),
@@ -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(),