feat(launcher): launch the game through the guarded lab

This commit is contained in:
N0VAN0M4LY committed 2026-11-29 15:02:39 +08:00
1 parent d633280e23
commit e41b73aaa3
25 files changed
+920 -23

No files matched your search

+1
View File
@@ -14,6 +14,7 @@ export default defineConfig({
// Utility process entries sit next to index.js, where the main process forks them.
input: {
index: resolve('src/main/index.ts'),
'build-worker': resolve('src/main/workers/build-worker.ts'),
'patch-check-worker': resolve('src/main/workers/patch-check-worker.ts'),
},
},
+14 -1
View File
@@ -2,7 +2,8 @@ import { app } from 'electron';
import { registerIpcHandlers } from './ipc/handlers.ts';
import { handleArtProtocol, registerArtScheme } from './services/background-art/art-protocol.ts';
import { startLauncherLogging } from './services/diagnostics/launcher-log.ts';
import { createMainWindow, showMainWindow } from './services/main-window.ts';
import { stopLaunch } from './services/launch/launch-controller.ts';
import { beginWindowQuit, createMainWindow, showMainWindow } from './services/main-window.ts';
/**
* Main process entry. Order:
@@ -26,6 +27,18 @@ if (!app.requestSingleInstanceLock()) {
startLauncherLogging();
app.on('second-instance', () => showMainWindow());
app.on('window-all-closed', () => app.quit());
let quitAfterLaunch = false;
app.on('before-quit', (event) => {
const cleanup = stopLaunch();
if (!cleanup) {
beginWindowQuit();
return;
}
event.preventDefault();
if (quitAfterLaunch) return;
quitAfterLaunch = true;
void cleanup.finally(() => app.quit());
});
// A top-level await on whenReady deadlocks an ESM main entry on Windows.
void app.whenReady().then(() => {
registerIpcHandlers();
+9
View File
@@ -9,6 +9,8 @@ import { inspectGameFolder, requireFolder } from '../services/game-folder/inspec
import { inspectTargetFolder } from '../services/game-folder/inspect-target-folder.ts';
import { cancelInstall, checkGameFolder, installGame } from '../services/install/install-game.ts';
import { defaultDataPath, readInstallRecord } from '../services/install/install-record.ts';
import { readInstalledLab } from '../services/launch/lab-handoff.ts';
import { getLaunchState, openServerStatus, startLaunch, stopLaunch } from '../services/launch/launch-controller.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts';
import { broadcast, handle } from './register.ts';
@@ -19,6 +21,7 @@ export function registerIpcHandlers(): void {
return {
version: app.getVersion(),
electron: process.versions.electron,
development: !app.isPackaged,
systemLocale: app.getLocale(),
userDataPath: app.getPath('userData'),
supportedGameVersions: recordedGameVersions(resources.patches),
@@ -72,6 +75,12 @@ export function registerIpcHandlers(): void {
return patchFeatures(resources.patches).map((feature) => ({ ...feature, patchIds: [...feature.patchIds] }));
});
handle('launch:getState', () => getLaunchState());
handle('launch:getLabInfo', () => readInstalledLab().catch(() => null));
handle('launch:start', () => startLaunch((state) => broadcast('event:launch-state', state)));
handle('launch:stop', async () => { await stopLaunch(); });
handle('launch:openServerStatus', () => openServerStatus());
handle('settings:get', () => getSettings());
handle('settings:update', async (patch) => {
const settings = await updateSettings(patch);
@@ -4,6 +4,7 @@ import { join } from 'node:path';
import { app, dialog, shell, type BrowserWindow } from 'electron';
import { zipSync } from 'fflate';
import { AppError } from '@shared/errors.ts';
import { getSettings } from '../config/settings-store.ts';
import { readInstallRecord } from '../install/install-record.ts';
import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts';
@@ -41,8 +42,9 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{
await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name));
}
}
const record = await readInstallRecord();
if (record) await addServerLogs(files, record.dataPath);
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath;
if (dataPath) await addServerLogs(files, dataPath);
const temporary = `${result.filePath}.${randomUUID()}.tmp`;
try {
@@ -0,0 +1,62 @@
import { join } from 'node:path';
import { utilityProcess } from 'electron';
import { AppError } from '@shared/errors.ts';
import type { BuildReply, BuildRequest } from '../../workers/build-protocol.ts';
import { forwardProcessOutput } from './process-output.ts';
export async function buildCopy(
request: BuildRequest,
signal: AbortSignal,
progress: (written: number, total: number, file?: string) => void,
): Promise<void> {
signal.throwIfAborted();
const worker = utilityProcess.fork(join(import.meta.dirname, 'build-worker.js'), [], {
serviceName: 'WTOffline game build',
stdio: 'pipe',
});
forwardProcessOutput(worker.stdout, 'build', 'info');
forwardProcessOutput(worker.stderr, 'build', 'error');
let writing = false;
const abort = (): void => {
// Once writes begin, finish the generation before accepting a retry.
if (!writing) worker.kill();
};
try {
await new Promise<void>((resolve, reject) => {
worker.once('exit', (code) => {
console.warn('[build] utility process exited:', code);
reject(signal.aborted ? signal.reason : new AppError('launch_build_failed'));
});
worker.on('message', (reply: BuildReply) => {
switch (reply.kind) {
case 'prepared':
if (signal.aborted) {
reject(signal.reason);
break;
}
progress(0, reply.total);
writing = true;
worker.postMessage({ kind: 'write' });
break;
case 'progress':
progress(reply.written, reply.total, reply.file);
break;
case 'written':
resolve();
break;
case 'failed':
reject(new AppError(reply.error));
break;
}
});
signal.addEventListener('abort', abort, { once: true });
worker.postMessage(request);
});
signal.throwIfAborted();
} finally {
signal.removeEventListener('abort', abort);
worker.removeAllListeners('exit');
worker.kill();
}
}
@@ -0,0 +1,177 @@
import { spawn } from 'node:child_process';
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 { forwardProcessOutput } from './process-output.ts';
const Configuration = z.object({
lab: z.string().min(1),
copy: z.string().min(1),
port: z.number().int().min(1).max(65535),
labUser: z.literal('wto-lab'),
});
const Status = z.object({
state: z.string(),
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;
readonly copyPath: string;
readonly controlPath: string;
readonly port: number;
}
export async function readInstalledLab(): Promise<Lab> {
if (app.isPackaged || process.platform !== 'win32') throw new AppError('launch_lab_required');
const programData = process.env['ProgramData'];
if (!programData) throw new AppError('launch_lab_missing');
const installPath = join(programData, 'WTOffline-lab');
try {
const config = Configuration.parse(JSON.parse(await readFile(join(installPath, 'lab.json'), 'utf8')));
const root = await realpath(config.lab);
const copyPath = await realpath(resolve(root, config.copy));
const relation = relative(root, copyPath);
if (!isAbsolute(config.lab) || !relation || relation.startsWith('..') || isAbsolute(relation)) {
throw new Error('The game copy is outside the lab.');
}
const executableFolder = await realpath(join(copyPath, 'win64'));
if (relative(copyPath, executableFolder).toLowerCase() !== 'win64') {
throw new Error('The lab executable folder points outside the copy.');
}
const controlPath = await realpath(join(root, 'automation'));
if (relative(root, controlPath).toLowerCase() !== 'automation') {
throw new Error('The lab control folder points outside the lab.');
}
for (const name of ['Run-GuardedGame.ps1', 'WtoNetworkGuard.exe']) {
if (!(await lstat(join(installPath, name))).isFile()) throw new Error(`Missing lab file: ${name}`);
}
return { installPath, copyPath, controlPath, port: config.port };
} catch (error) {
console.warn('[lab] the installed automation is unavailable:', error);
throw new AppError('launch_lab_missing');
}
}
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')));
} catch {
return 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;
});
}
type LabPhase = 'starting-server' | 'starting-game' | 'running' | 'server-exited';
/** The installed guard owns the game process and observes the stop request. */
export async function runLab(
lab: Lab,
stockPath: string,
dataPath: string,
signal: AbortSignal,
publish: (phase: LabPhase) => void,
): Promise<void> {
signal.throwIfAborted();
const repository = resolve(app.getAppPath(), '..', '..');
const child = spawn('powershell.exe', [
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
'-File', join(repository, 'tools', 'lab', 'Start-LabTest.ps1'),
'-SkipBuild', '-Stock', stockPath, '-Data', dataPath, '-Install', lab.installPath,
], { cwd: repository, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
let serverPid: number | null = null;
let running = false;
let processClosed = false;
let serverExited = false;
let occupied = false;
let failures = 0;
let checking = false;
let stopSent = false;
const requestStop = (): void => {
if (!running || stopSent || processClosed) return;
stopSent = true;
void stopGame(lab).catch((error: unknown) => {
stopSent = false;
console.error('[lab] could not request a guarded stop:', error);
});
};
const observe = (line: string): void => {
if (/Port \d+ is already in use\./.test(line)) occupied = true;
const ready = /^\[WTO lab test\] Local server pid (\d+) listening/.exec(line);
if (ready) {
serverPid = Number(ready[1]);
publish('starting-game');
}
if (line.startsWith('[WTO lab test] Game running (pid ')) {
running = true;
publish('running');
if (signal.aborted) requestStop();
}
if (line.startsWith('[WTO lab test] Run ')) running = false;
};
forwardProcessOutput(child.stdout, 'lab', 'info', observe);
forwardProcessOutput(child.stderr, 'lab', 'error', observe);
publish('starting-server');
signal.addEventListener('abort', requestStop, { once: true });
const interval = setInterval(() => {
if (!running || !serverPid || processClosed || checking) return;
if (signal.aborted || serverExited) {
requestStop();
return;
}
checking = true;
void isReady(lab.port, serverPid).then((ready) => {
if (!running || processClosed) return;
failures = ready ? 0 : failures + 1;
if (failures < 3) return;
serverExited = true;
publish('server-exited');
requestStop();
}).finally(() => { checking = false; });
}, 1000);
try {
const code = await new Promise<number | null>((done, fail) => {
child.once('error', fail);
child.once('close', done);
});
processClosed = true;
if (signal.aborted) return;
if (occupied) throw new AppError('launch_port_busy');
if (serverExited) throw new AppError('launch_server_exited');
const status = serverPid === null ? null : await readStatus(lab);
if (code !== 0 || status?.state !== 'finished' || (status.guardExitCode ?? 0) !== 0 ||
status.message.startsWith('EXTERNAL TCP CONNECTION')) {
throw new AppError('launch_lab_failed');
}
} finally {
processClosed = true;
clearInterval(interval);
signal.removeEventListener('abort', requestStop);
}
}
@@ -0,0 +1,157 @@
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 { executableVersion, GAME_FILES, isInSteamLibrary } from '@wto/patcher';
import { AppError } from '@shared/errors.ts';
import type { LaunchState } from '@shared/schemas/launch.ts';
import { getSettings } from '../config/settings-store.ts';
import { readInstallRecord } from '../install/install-record.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
import { buildCopy } from './build-copy.ts';
import { labStatusUrl, readInstalledLab, runLab } from './lab-handoff.ts';
const execute = promisify(execFile);
interface LaunchJob {
readonly stop: AbortController;
readonly report: (state: LaunchState) => void;
done: Promise<void>;
}
let active: LaunchJob | null = null;
let state: LaunchState = { phase: 'ready' };
export function getLaunchState(): LaunchState {
return state;
}
export function startLaunch(report: LaunchJob['report']): LaunchState {
if (active) throw new AppError('launch_busy');
const job = { stop: new AbortController(), report, done: Promise.resolve() };
active = job;
update(job, { phase: 'checking' });
job.done = launch(job).catch((error: unknown) => {
const port = state.port;
const context = port === undefined ? {} : { port };
if (job.stop.signal.aborted) {
update(job, { phase: 'ready' });
return;
}
console.error('[launch] launch failed:', error);
const code = error instanceof AppError ? error.code : 'launch_lab_failed';
switch (code) {
case 'launch_port_busy':
update(job, { phase: 'port-busy', ...context });
break;
case 'launch_server_exited':
update(job, { phase: 'server-exited', ...context });
break;
default:
update(job, { phase: 'failed', error: code, ...context });
break;
}
}).finally(() => {
active = null;
});
return state;
}
export function stopLaunch(): Promise<void> | null {
const job = active;
if (!job) return null;
if (!job.stop.signal.aborted) {
update(job, { ...state, phase: 'stopping' });
job.stop.abort();
}
return job.done;
}
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));
}
function update(job: LaunchJob, next: LaunchState): void {
state = next;
job.report(next);
}
async function launch(job: LaunchJob): Promise<void> {
const signal = job.stop.signal;
const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]);
if (!record) throw new AppError('launch_no_copy');
if (!settings.developerMode) throw new AppError('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) {
update(job, { phase: 'version-changed', actualVersion: currentVersion });
return;
}
const lab = await readInstalledLab();
const stockPath = settings.labStockPath ?? record.stockBackupPath;
const dataPath = settings.labDataPath ?? record.dataPath;
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('..'))) {
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),
readVersion(stockPath, signal),
execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal }),
]);
signal.throwIfAborted();
if (!labVersion || labVersion !== stockVersion) throw new AppError('launch_lab_version');
if (/^"aces\.exe",/im.test(games.stdout)) throw new AppError('launch_game_running');
await checkPort(lab.port);
signal.throwIfAborted();
update(job, { phase: 'building', port: lab.port });
await buildCopy({
kind: 'build',
stockPath,
copyPath: lab.copyPath,
dataPath,
port: lab.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 }),
});
});
await runLab(lab, stockPath, dataPath, signal, (phase) => {
if (!signal.aborted) update(job, { phase, port: lab.port });
if (phase === 'running' && !signal.aborted && settings.afterGameStarts === 'minimize') {
for (const window of BrowserWindow.getAllWindows()) window.minimize();
}
});
update(job, { phase: 'ready' });
}
async function readVersion(folder: string, signal: AbortSignal): Promise<string | null> {
try {
return executableVersion(await readFile(join(folder, GAME_FILES.executable), { signal }));
} catch (error) {
signal.throwIfAborted();
console.warn('[launch] reading the game version failed:', folder, error);
return null;
}
}
async function checkPort(port: number): Promise<void> {
await new Promise<void>((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()));
});
}
@@ -0,0 +1,16 @@
import { createInterface } from 'node:readline';
/** Preserve complete lines when a process splits or combines them across writes. */
export function forwardProcessOutput(
stream: NodeJS.ReadableStream | null,
prefix: string,
level: 'info' | 'error',
onLine?: (line: string) => void,
): void {
if (!stream) return;
const reader = createInterface({ input: stream, crlfDelay: Infinity, terminal: false });
reader.on('line', (line) => {
console[level](`[${prefix}] ${line}`);
onLine?.(line);
});
}
+35 -1
View File
@@ -1,5 +1,6 @@
import { join } from 'node:path';
import { BrowserWindow, shell } from 'electron';
import { app, BrowserWindow, Menu, shell, Tray } from 'electron';
import { getSettings } from './config/settings-store.ts';
/**
* The launcher's single window: a fixed size without the system frame, like the game's own
@@ -13,6 +14,24 @@ const CONTENT_HEIGHT = 720;
const BACKGROUND = '#13191b';
let mainWindow: BrowserWindow | null = null;
let tray: Tray | null = null;
let quitting = false;
export function beginWindowQuit(): void {
quitting = true;
tray?.destroy();
tray = null;
}
async function hideToTray(window: BrowserWindow): Promise<void> {
if (!tray) {
tray = new Tray(await app.getFileIcon(process.execPath, { size: 'small' }));
tray.setToolTip(app.getName());
tray.setContextMenu(Menu.buildFromTemplate([{ role: 'quit' }]));
tray.on('click', () => showMainWindow());
}
if (!window.isDestroyed()) window.hide();
}
export function createMainWindow(): BrowserWindow {
const window = new BrowserWindow({
@@ -39,6 +58,20 @@ export function createMainWindow(): BrowserWindow {
return { action: 'deny' };
});
window.webContents.on('will-navigate', (event) => event.preventDefault());
let handlingClose = false;
window.on('close', (event) => {
if (quitting) return;
event.preventDefault();
if (handlingClose) return;
handlingClose = true;
void getSettings().then(async (settings) => {
if (settings.windowClose === 'tray') await hideToTray(window);
else app.quit();
}).catch((error: unknown) => {
console.warn('[window] the close action failed:', error);
app.quit();
}).finally(() => { handlingClose = false; });
});
window.on('closed', () => {
if (mainWindow === window) mainWindow = null;
});
@@ -54,5 +87,6 @@ export function createMainWindow(): BrowserWindow {
export function showMainWindow(): void {
const window = mainWindow ?? createMainWindow();
if (window.isMinimized()) window.restore();
if (!window.isVisible()) window.show();
window.focus();
}
@@ -0,0 +1,19 @@
import type { AppErrorCode } from '@shared/errors.ts';
export interface BuildRequest {
readonly kind: 'build';
readonly stockPath: string;
readonly copyPath: string;
readonly dataPath: string;
readonly port: number;
readonly patches: string;
readonly networkHookLibrary: string;
readonly acceptedUnavailable: readonly string[];
}
export type BuildCommand = BuildRequest | { readonly kind: 'write' };
export type BuildReply =
| { readonly kind: 'prepared'; readonly total: number }
| { readonly kind: 'progress'; readonly written: number; readonly total: number; readonly file: string }
| { readonly kind: 'written' }
| { readonly kind: 'failed'; readonly error: AppErrorCode };
@@ -0,0 +1,53 @@
import { readFileSync } from 'node:fs';
import type { MessageEvent } from 'electron';
import { assertWritableCopy, buildGameCopy, readStockGameFiles, writeGameCopy, type GameCopyFile } from '@wto/patcher';
import { multiVehiclePackIds } from '@wto/server';
import type { BuildCommand, BuildReply, BuildRequest } from './build-protocol.ts';
let prepared: { readonly copyPath: string; readonly files: readonly GameCopyFile[] } | null = null;
function send(reply: BuildReply): void {
process.parentPort.postMessage(reply);
}
function build(request: BuildRequest): void {
assertWritableCopy(request.stockPath, request.copyPath);
const result = buildGameCopy({
stock: readStockGameFiles(request.stockPath),
patches: request.patches,
networkHookLibrary: readFileSync(request.networkHookLibrary),
port: request.port,
multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info),
placeholderDecals: true,
});
const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures];
const accepted = new Set(request.acceptedUnavailable);
if (result.blocking.length > 0 || unavailable.some((failure) => !accepted.has(failure.patchId))) {
console.error('[build] the copy has unaccepted or essential failures:', unavailable);
send({ kind: 'failed', error: 'launch_build_unavailable' });
return;
}
prepared = { copyPath: request.copyPath, files: result.files };
send({ kind: 'prepared', total: prepared.files.length });
}
process.parentPort.on('message', (event: MessageEvent) => {
const command = event.data as BuildCommand;
try {
if (command.kind === 'build') {
build(command);
return;
}
if (!prepared) throw new Error('No build is ready to write.');
const { copyPath, files } = prepared;
prepared = null;
for (const [index, file] of files.entries()) {
writeGameCopy(copyPath, [file]);
send({ kind: 'progress', written: index + 1, total: files.length, file: file.path });
}
send({ kind: 'written' });
} catch (error) {
console.error('[build] preparing the game copy failed:', error);
send({ kind: 'failed', error: 'launch_build_failed' });
}
});
+34 -7
View File
@@ -2,10 +2,11 @@ import { useEffect, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import type { IpcOutput } from '@shared/ipc/contract.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import 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';
import { ipcOn } from './ipc.ts';
import { ipcInvoke, ipcOn } from './ipc.ts';
import { AboutPage } from './pages/about/AboutPage.tsx';
import { CopySummary } from './pages/copies/CopySummary.tsx';
import { FeatureStatus } from './pages/copies/FeatureStatus.tsx';
@@ -17,8 +18,10 @@ import { useInstallWizard } from './pages/install/useInstallWizard.ts';
import { WizardMain } from './pages/install/WizardMain.tsx';
import { WizardSide } from './pages/install/WizardSide.tsx';
import { wizardBar } from './pages/install/wizard-bar.ts';
import { DeveloperSettings } from './pages/settings/DeveloperSettings.tsx';
import { DiagnosticsSettings } from './pages/settings/DiagnosticsSettings.tsx';
import { GeneralSettings } from './pages/settings/GeneralSettings.tsx';
import { LaunchSettings } from './pages/settings/LaunchSettings.tsx';
import { Background } from './shell/Background.tsx';
import { BottomBar } from './shell/BottomBar.tsx';
import type { BarModel } from './shell/bar-model.ts';
@@ -52,6 +55,7 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A
const { message, report } = useErrorMessage();
const [settings, setSettings] = useState(initialSettings);
const [record, setRecord] = useState(initialRecord);
const [launch, setLaunch] = useState<LaunchState>({ phase: 'ready' });
const [route, setRoute] = useState<Route>(START_ROUTE);
const supported = info.supportedGameVersions;
@@ -68,8 +72,25 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A
useEffect(() => ipcOn('event:settings-changed', setSettings), []);
useEffect(() => applyLanguage(resolveLanguage(settings.language, info.systemLocale)), [settings.language, info.systemLocale]);
useEffect(() => {
let mounted = true;
let receivedEvent = false;
const dispose = ipcOn('event:launch-state', (state) => {
receivedEvent = true;
setLaunch(state);
});
ipcInvoke('launch:getState').then((state) => {
if (mounted && !receivedEvent) setLaunch(state);
}).catch(report);
return () => { mounted = false; dispose(); };
}, [report]);
const go = (to: Destination): void => setRoute((current) => navigate(current, to));
const home = homeBar(record, t, wizard.start);
const home = homeBar(record, launch, t, wizard.start, {
start: () => { ipcInvoke('launch:start').catch(report); },
stop: () => { ipcInvoke('launch:stop').catch(report); },
checkVersion: () => go({ page: 'copies', section: 'features' }),
});
const view = ((): View => {
if (wizard.active) {
@@ -90,14 +111,20 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A
};
case 'about':
return { side: homeSide, main: <AboutPage launcherVersion={info.version} supportedVersions={supported} />, bar: home };
case 'settings':
case 'settings': {
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'} />,
dev: <DeveloperSettings settings={settings} onError={report} />,
};
return {
side: <SubNav sections={SETTINGS_SECTIONS} active={route.settings} label={(section) => t(`settings.sections.${section}`)} onSelect={(section) => go({ page: 'settings', section })} />,
main: route.settings === 'diag'
? <DiagnosticsSettings onError={report} />
: <GeneralSettings settings={settings} pictures={backgrounds.pictures} onError={report} />,
side: <SubNav sections={sections} active={route.settings} label={(section) => t(`settings.sections.${section}`)} onSelect={(section) => go({ page: 'settings', section })} />,
main: content[route.settings],
bar: home,
};
}
case 'copies': {
const side = (
<>
@@ -62,9 +62,27 @@
"install": "Install",
"ready": "Ready",
"readyMissing": "Ready · {{count}} features unavailable",
"readyDetail": "Game {{version}} · Launch unavailable",
"readyDetail": "Game {{version}}",
"launch": "Launch"
},
"launch": {
"checking": "Checking the game copy",
"building": "Generating game files",
"starting-server": "Starting local server",
"starting-game": "Starting game",
"starting": "Starting…",
"running": "Game running",
"runningDetail": "Local server · Port {{port}}",
"stopping": "Stopping game",
"cancel": "Cancel",
"stop": "End game",
"retry": "Retry",
"check": "Check",
"version-changed": "The copy version has changed",
"versionDetail": "Game version {{version}}",
"port-busy": "Port {{port}} is already in use",
"server-exited": "The local server exited unexpectedly"
},
"folder": {
"none": "Not selected",
"choose": "Browse…",
@@ -199,8 +217,33 @@
"settings": {
"sections": {
"general": "General",
"launch": "Launch",
"dev": "Developer",
"diag": "Diagnostics"
},
"windowClose": "When closing the window",
"windowQuit": "Quit launcher",
"windowTray": "Minimize to system tray",
"afterGameStarts": "When the game starts",
"windowMinimize": "Minimize launcher",
"windowKeep": "Keep window open",
"launch": {
"port": "Local server port",
"portHint": "Port set by the installed lab automation",
"exit": "When the game exits",
"exitHint": "Isolated launch",
"automatic": "Close local server"
},
"developer": {
"mode": "Developer mode",
"modeHint": "Launches the lab copy under the wto-lab Windows account",
"enabled": "Enabled",
"stock": "Stock backup",
"stockHint": "Defaults to the selected copy’s stock backup",
"data": "Lab data folder",
"dataHint": "Defaults to the selected copy’s data folder",
"reset": "Restore default"
},
"diagnostics": {
"logs": "Logs",
"logsHint": "Logs recorded by the launcher",
@@ -208,7 +251,9 @@
"export": "Export diagnostics",
"exportHint": "Save logs, settings and the installation record to a ZIP file",
"save": "Export…",
"saved": "Diagnostics saved to {{path}}."
"saved": "Diagnostics saved to {{path}}.",
"serverStatus": "Local server status",
"openStatus": "Open in browser"
},
"language": "Language",
"languageHint": "Display language of the launcher"
@@ -281,6 +326,18 @@
"internal_error": "An internal launcher error occurred.",
"logs_folder_open_failed": "The launcher log folder could not be opened.",
"diagnostics_export_failed": "The diagnostics archive could not be saved.",
"launch_no_copy": "A game copy must be installed before launching.",
"launch_busy": "A launch is already in progress.",
"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_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_exited": "The local server is unavailable.",
"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}}",
@@ -62,9 +62,27 @@
"install": "安装",
"ready": "就绪",
"readyMissing": "就绪 · {{count}} 项功能不可用",
"readyDetail": "游戏 {{version}} · 启动暂不可用",
"readyDetail": "游戏 {{version}}",
"launch": "启动"
},
"launch": {
"checking": "正在检查副本",
"building": "正在生成游戏文件",
"starting-server": "正在启动本地服务器",
"starting-game": "正在启动游戏",
"starting": "启动中…",
"running": "游戏运行中",
"runningDetail": "本地服务器 · 端口 {{port}}",
"stopping": "正在结束游戏",
"cancel": "取消",
"stop": "结束游戏",
"retry": "重试",
"check": "检查",
"version-changed": "副本版本已变更",
"versionDetail": "游戏版本 {{version}}",
"port-busy": "端口 {{port}} 已被占用",
"server-exited": "本地服务器意外退出"
},
"folder": {
"none": "未选择",
"choose": "浏览…",
@@ -199,8 +217,33 @@
"settings": {
"sections": {
"general": "常规",
"launch": "启动",
"dev": "开发者",
"diag": "诊断"
},
"windowClose": "关闭窗口时",
"windowQuit": "退出启动器",
"windowTray": "最小化到系统托盘",
"afterGameStarts": "游戏启动后",
"windowMinimize": "最小化启动器",
"windowKeep": "保持窗口",
"launch": {
"port": "本地服务器端口",
"portHint": "使用已安装实验自动化的端口设置",
"exit": "游戏退出后",
"exitHint": "隔离启动",
"automatic": "关闭本地服务器"
},
"developer": {
"mode": "开发模式",
"modeHint": "以 wto-lab 用户身份启动实验副本",
"enabled": "启用",
"stock": "原版文件备份",
"stockHint": "默认使用当前副本的原版文件备份",
"data": "实验数据目录",
"dataHint": "默认使用当前副本的数据目录",
"reset": "恢复默认"
},
"diagnostics": {
"logs": "日志",
"logsHint": "启动器运行日志",
@@ -208,7 +251,9 @@
"export": "导出诊断信息",
"exportHint": "导出包含日志、设置和安装记录的 ZIP 文件",
"save": "导出…",
"saved": "诊断信息已保存到 {{path}}。"
"saved": "诊断信息已保存到 {{path}}。",
"serverStatus": "本地服务器状态页",
"openStatus": "在浏览器中打开"
},
"language": "语言",
"languageHint": "启动器界面的显示语言"
@@ -281,6 +326,18 @@
"internal_error": "启动器内部错误。",
"logs_folder_open_failed": "无法打开启动器日志文件夹。",
"diagnostics_export_failed": "无法保存诊断信息。",
"launch_no_copy": "启动前需要安装游戏副本。",
"launch_busy": "启动流程正在运行。",
"launch_lab_required": "请启用开发模式以通过隔离实验副本启动。",
"launch_lab_missing": "无法读取隔离实验自动化配置。",
"launch_lab_version": "实验副本和原版文件备份必须使用同一游戏版本。",
"launch_lab_failed": "隔离启动失败。请查看启动器日志。",
"launch_game_running": "已有游戏进程在运行。",
"launch_copy_in_steam": "启动需使用 Steam 目录外的副本和数据目录。",
"launch_build_failed": "无法生成游戏文件。",
"launch_build_unavailable": "生成游戏文件时发现需要重新确认的不可用补丁。",
"launch_port_busy": "本地服务器端口已被占用。",
"launch_server_exited": "本地服务器不可用。",
"settings_write_failed": "无法保存设置。",
"folder_unreadable": "无法读取文件夹:{{path}}",
"not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}",
@@ -1,13 +1,72 @@
import type { TFunction } from 'i18next';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { LaunchState } from '@shared/schemas/launch.ts';
import type { BarModel } from '../../shell/bar-model.ts';
import { missingFeatures } from '../copies/missing-features.ts';
/**
* The bottom bar outside the wizard: install before the first installation, launch after it.
* The launch action is disabled until the launcher can start a copy.
*/
export function homeBar(record: InstallRecord | null, t: TFunction, onInstall: () => void): BarModel {
interface LaunchActions {
readonly start: () => void;
readonly stop: () => void;
readonly checkVersion: () => void;
}
/** The installation and launch actions shown outside the wizard. */
export function homeBar(
record: InstallRecord | null,
state: LaunchState,
t: TFunction,
onInstall: () => void,
actions: LaunchActions,
): BarModel {
const launch = { label: t('bar.launch'), onClick: actions.start };
const retry = { label: t('launch.retry'), onClick: actions.start };
const starting = { label: t('launch.starting'), disabled: true };
const progress = { value: state.filesWritten ?? 0, max: state.filesTotal || null };
switch (state.phase) {
case 'checking':
case 'building':
return {
tone: 'busy',
title: state.phase === 'checking' ? t('launch.checking') : t('launch.building'),
detail: state.file,
progress,
primary: starting,
secondary: { label: t('launch.cancel'), onClick: actions.stop },
};
case 'starting-server':
case 'starting-game':
case 'stopping':
return {
tone: 'busy',
title: t(`launch.${state.phase}`),
progress: { value: 0, max: null },
primary: starting,
};
case 'running':
return {
tone: 'ok',
title: t('launch.running'),
detail: t('launch.runningDetail', { port: state.port }),
primary: { label: t('launch.running'), disabled: true },
secondary: { label: t('launch.stop'), onClick: actions.stop },
};
case 'port-busy':
return { tone: 'bad', title: t('launch.port-busy', { port: state.port }), primary: retry };
case 'server-exited':
return { tone: 'bad', title: t('launch.server-exited'), primary: retry };
case 'version-changed':
return {
tone: 'warn',
title: t('launch.version-changed'),
detail: t('launch.versionDetail', { version: state.actualVersion ?? t('source.versionUnknown') }),
primary: { label: t('launch.check'), onClick: actions.checkVersion },
};
case 'failed':
return { tone: 'bad', title: t(`errors.${state.error ?? 'launch_lab_failed'}`), primary: retry };
case 'ready':
break;
}
if (!record) {
return {
tone: 'idle',
@@ -21,6 +80,6 @@ export function homeBar(record: InstallRecord | null, t: TFunction, onInstall: (
tone: missing ? 'warn' : 'ok',
title: missing ? t('bar.readyMissing', { count: missing }) : t('bar.ready'),
detail: t('bar.readyDetail', { version: record.gameVersion ?? t('source.versionUnknown') }),
primary: { label: t('bar.launch'), disabled: true },
primary: launch,
};
}
@@ -0,0 +1,35 @@
import { useTranslation } from 'react-i18next';
import type { Settings, SettingsPatch } from '@shared/schemas/settings.ts';
import { FolderField } from '../../components/FolderField.tsx';
import { Row } from '../../components/Row.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
interface DeveloperSettingsProps {
readonly settings: Settings;
readonly onError: (error: unknown) => void;
}
export function DeveloperSettings({ settings, onError }: DeveloperSettingsProps) {
const { t } = useTranslation();
const update = (patch: SettingsPatch): void => { ipcInvoke('settings:update', patch).catch(onError); };
return (
<Sheet title={t('settings.sections.dev')}>
<Row label={t('settings.developer.mode')} hint={t('settings.developer.modeHint')}>
<label className="check check-inline">
<input type="checkbox" checked={settings.developerMode} onChange={(event) => update({ developerMode: event.target.checked })} />
{t('settings.developer.enabled')}
</label>
</Row>
<Row label={t('settings.developer.stock')} hint={t('settings.developer.stockHint')}>
<FolderField path={settings.labStockPath} dialogTitle={t('settings.developer.stock')} onChosen={(path) => update({ labStockPath: path })} onError={onError} />
{settings.labStockPath && <button type="button" className="button" onClick={() => update({ labStockPath: null })}>{t('settings.developer.reset')}</button>}
</Row>
<Row label={t('settings.developer.data')} hint={t('settings.developer.dataHint')}>
<FolderField path={settings.labDataPath} dialogTitle={t('settings.developer.data')} onChosen={(path) => update({ labDataPath: path })} onError={onError} />
{settings.labDataPath && <button type="button" className="button" onClick={() => update({ labDataPath: null })}>{t('settings.developer.reset')}</button>}
</Row>
</Sheet>
);
}
@@ -5,10 +5,11 @@ import { Sheet } from '../../components/Sheet.tsx';
import { ipcInvoke } from '../../ipc.ts';
interface DiagnosticsSettingsProps {
readonly serverRunning: boolean;
readonly onError: (error: unknown) => void;
}
export function DiagnosticsSettings({ onError }: DiagnosticsSettingsProps) {
export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSettingsProps) {
const { t } = useTranslation();
const [exporting, setExporting] = useState(false);
const [savedPath, setSavedPath] = useState<string | null>(null);
@@ -38,6 +39,11 @@ export function DiagnosticsSettings({ onError }: DiagnosticsSettingsProps) {
{t('settings.diagnostics.save')}
</button>
</Row>
<Row label={t('settings.diagnostics.serverStatus')}>
<button type="button" className="button" disabled={!serverRunning} onClick={() => ipcInvoke('launch:openServerStatus').catch(onError)}>
{t('settings.diagnostics.openStatus')}
</button>
</Row>
{savedPath && <p className="small" role="status">{t('settings.diagnostics.saved', { path: savedPath })}</p>}
</Sheet>
);
@@ -38,6 +38,18 @@ export function GeneralSettings({ settings, pictures, onError }: GeneralSettings
<Row label={t('settings.language')} hint={t('settings.languageHint')}>
<LanguageMenu value={settings.language} onError={onError} plain />
</Row>
<Row label={t('settings.windowClose')}>
<select className="select" value={settings.windowClose} onChange={(event) => update({ windowClose: event.target.value === 'tray' ? 'tray' : 'quit' })}>
<option value="quit">{t('settings.windowQuit')}</option>
<option value="tray">{t('settings.windowTray')}</option>
</select>
</Row>
<Row label={t('settings.afterGameStarts')}>
<select className="select" value={settings.afterGameStarts} onChange={(event) => update({ afterGameStarts: event.target.value === 'keep' ? 'keep' : 'minimize' })}>
<option value="minimize">{t('settings.windowMinimize')}</option>
<option value="keep">{t('settings.windowKeep')}</option>
</select>
</Row>
<Row label={t('background.official')} hint={t('background.officialHint')}>
<label className="check check-inline">
<input type="checkbox" checked={settings.officialWallpapers} onChange={(event) => update({ officialWallpapers: event.target.checked })} />
@@ -0,0 +1,29 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { IpcOutput } from '@shared/ipc/contract.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 }) {
const { t } = useTranslation();
const [lab, setLab] = useState<IpcOutput<'launch:getLabInfo'>>(null);
useEffect(() => {
let mounted = true;
ipcInvoke('launch:getLabInfo').then((info) => {
if (mounted) setLab(info);
}).catch(onError);
return () => { mounted = false; };
}, [onError]);
return (
<Sheet title={t('settings.sections.launch')}>
<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>
);
}
@@ -9,7 +9,7 @@ export type PageId = (typeof PAGES)[number];
export const COPY_SECTIONS = ['summary', 'features'] as const;
export type CopySection = (typeof COPY_SECTIONS)[number];
export const SETTINGS_SECTIONS = ['general', 'diag'] as const;
export const SETTINGS_SECTIONS = ['general', 'launch', 'diag', 'dev'] as const;
export type SettingsSection = (typeof SETTINGS_SECTIONS)[number];
export interface Route {
+12
View File
@@ -16,6 +16,18 @@ export const APP_ERROR_CODES = [
'settings_write_failed',
'logs_folder_open_failed',
'diagnostics_export_failed',
'launch_no_copy',
'launch_busy',
'launch_lab_required',
'launch_lab_missing',
'launch_lab_version',
'launch_lab_failed',
'launch_game_running',
'launch_copy_in_steam',
'launch_build_failed',
'launch_build_unavailable',
'launch_port_busy',
'launch_server_exited',
/** 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). */
+2
View File
@@ -12,6 +12,8 @@ export const IPC_CHANNEL_PREFIXES = [
'dialog:',
/** Installing the offline version: looking at the chosen folders, copying, patching. */
'install:',
/** Starting and stopping the active copy. */
'launch:',
/** The launcher's own settings. */
'settings:',
/** The launcher window itself (it draws its own title bar). */
+23
View File
@@ -10,6 +10,7 @@ import {
PatchFeatureSchema,
TargetFolderInspectionSchema,
} from '../schemas/install.ts';
import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts';
import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts';
/**
@@ -25,6 +26,7 @@ export const ipcContract = {
output: z.object({
version: z.string(),
electron: z.string(),
development: z.boolean(),
/** The operating system's preferred language, as Electron reports it (e.g. "zh-CN"). */
systemLocale: z.string(),
userDataPath: z.string(),
@@ -93,6 +95,26 @@ export const ipcContract = {
input: z.void(),
output: z.array(PatchFeatureSchema),
},
'launch:getState': {
input: z.void(),
output: LaunchStateSchema,
},
'launch:getLabInfo': {
input: z.void(),
output: LabInfoSchema.nullable(),
},
'launch:start': {
input: z.void(),
output: LaunchStateSchema,
},
'launch:stop': {
input: z.void(),
output: z.void(),
},
'launch:openServerStatus': {
input: z.void(),
output: z.void(),
},
'settings:get': {
input: z.void(),
output: SettingsSchema,
@@ -114,6 +136,7 @@ export const ipcContract = {
export const ipcEvents = {
'event:settings-changed': SettingsSchema,
'event:install-progress': InstallProgressSchema,
'event:launch-state': LaunchStateSchema,
} as const;
export type IpcChannel = keyof typeof ipcContract;
@@ -0,0 +1,22 @@
import { z } from 'zod';
import { APP_ERROR_CODES } from '../errors.ts';
export const LaunchStateSchema = z.object({
phase: z.enum([
'ready', 'checking', 'building', 'starting-server', 'starting-game', 'running',
'stopping', 'port-busy', 'version-changed', 'server-exited', 'failed',
]),
port: z.number().int().min(1).max(65535).optional(),
filesWritten: z.number().int().nonnegative().optional(),
filesTotal: z.number().int().nonnegative().optional(),
file: z.string().optional(),
actualVersion: z.string().nullable().optional(),
error: z.enum(APP_ERROR_CODES).optional(),
});
export type LaunchState = z.output<typeof LaunchStateSchema>;
export const LabInfoSchema = z.object({
copyPath: z.string(),
port: z.number().int().min(1).max(65535),
});
@@ -3,6 +3,9 @@ import { LANGUAGE_CHOICES } from '../languages.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();
/** The launcher's own settings (not the game's, not the local service's tuning). */
export const SettingsSchema = z.object({
@@ -11,6 +14,11 @@ export const SettingsSchema = z.object({
background: BackgroundChoiceSchema.default(BACKGROUND_RANDOM),
/** Fetch wallpapers from the game website's public gallery. */
officialWallpapers: z.boolean().default(true),
windowClose: WindowCloseSchema.default('quit'),
afterGameStarts: AfterGameStartsSchema.default('minimize'),
developerMode: z.boolean().default(true),
labStockPath: LabPathSchema.default(null),
labDataPath: LabPathSchema.default(null),
});
export type Settings = z.output<typeof SettingsSchema>;
@@ -20,6 +28,11 @@ export const SettingsPatchSchema = z.object({
language: LanguageChoiceSchema.optional(),
background: BackgroundChoiceSchema.optional(),
officialWallpapers: z.boolean().optional(),
windowClose: WindowCloseSchema.optional(),
afterGameStarts: AfterGameStartsSchema.optional(),
developerMode: z.boolean().optional(),
labStockPath: LabPathSchema.optional(),
labDataPath: LabPathSchema.optional(),
});
export type SettingsPatch = z.output<typeof SettingsPatchSchema>;