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,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'));
});
});
});
}