From ef3648cb1357f796de27af072ad0e0a1df3c34ed Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:24:21 +0800 Subject: [PATCH] feat(launcher): add maintenance for installed game copies --- apps/launcher/src/main/ipc/handlers.ts | 15 +- .../main/services/copies/change-copy-files.ts | 76 +++++ .../main/services/copies/copy-maintenance.ts | 267 ++++++++++++++++++ .../src/main/services/install/copy-game.ts | 11 +- .../src/main/services/install/install-game.ts | 13 +- .../main/services/install/install-record.ts | 36 ++- .../main/services/launch/launch-controller.ts | 14 +- apps/launcher/src/renderer/src/App.tsx | 4 + .../src/renderer/src/i18n/locales/en.json | 40 ++- .../src/renderer/src/i18n/locales/zh-CN.json | 40 ++- .../src/pages/copies/CopyMaintenance.tsx | 113 ++++++++ .../src/renderer/src/shell/navigation.ts | 2 +- .../src/renderer/src/styles/pages.css | 18 ++ apps/launcher/src/shared/errors.ts | 6 + apps/launcher/src/shared/ipc/contract.ts | 14 + apps/launcher/src/shared/schemas/install.ts | 3 + .../src/shared/schemas/maintenance.ts | 24 ++ 17 files changed, 672 insertions(+), 24 deletions(-) create mode 100644 apps/launcher/src/main/services/copies/change-copy-files.ts create mode 100644 apps/launcher/src/main/services/copies/copy-maintenance.ts create mode 100644 apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx create mode 100644 apps/launcher/src/shared/schemas/maintenance.ts diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index 95df0ac..2139e2d 100644 --- a/apps/launcher/src/main/ipc/handlers.ts +++ b/apps/launcher/src/main/ipc/handlers.ts @@ -3,6 +3,7 @@ import { patchFeatures, recordedGameVersions } from '@wto/patcher'; import { AppError } from '@shared/errors.ts'; import { listBackgroundPictures } from '../services/background-art/art-catalog.ts'; import { getSettings, updateSettings } from '../services/config/settings-store.ts'; +import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress } from '../services/copies/copy-maintenance.ts'; import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts'; import { measureFolder } from '../services/game-folder/folder-size.ts'; import { inspectGameFolder, requireFolder } from '../services/game-folder/inspect-game-folder.ts'; @@ -69,6 +70,7 @@ export function registerIpcHandlers(): void { handle('install:checkPatches', ({ gamePath, dataPath }) => checkGameFolder(gamePath, dataPath)); handle('install:start', async (request) => { + if (maintenanceInProgress()) throw new AppError('maintenance_busy'); const record = await installGame(request, (progress) => broadcast('event:install-progress', progress)); broadcast('event:copies-changed', await listCopies()); return record; @@ -92,9 +94,20 @@ export function registerIpcHandlers(): void { return registry; }); + handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id)); + handle('copies:maintain', async (request) => { + const updated = await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress)); + broadcast('event:copies-changed', updated); + return updated; + }); + handle('copies:cancelMaintenance', () => cancelMaintenance()); + handle('launch:getState', () => getLaunchState()); handle('launch:getLabInfo', () => readInstalledLab().catch(() => null)); - handle('launch:start', () => startLaunch((state) => broadcast('event:launch-state', state))); + handle('launch:start', () => { + if (maintenanceInProgress()) throw new AppError('maintenance_busy'); + return startLaunch((state) => broadcast('event:launch-state', state)); + }); handle('launch:stop', async () => { await stopLaunch(); }); handle('launch:openServerStatus', () => openServerStatus()); diff --git a/apps/launcher/src/main/services/copies/change-copy-files.ts b/apps/launcher/src/main/services/copies/change-copy-files.ts new file mode 100644 index 0000000..195c1f0 --- /dev/null +++ b/apps/launcher/src/main/services/copies/change-copy-files.ts @@ -0,0 +1,76 @@ +import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises'; +import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path'; +import { canonicalCopyPath, copyPathContains } from '../install/install-record.ts'; + +export async function fileInfo(path: string) { + try { + return await lstat(path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + return null; + } +} + +export async function stagedPath(root: string, name: string): Promise { + const part = normalize(name); + if (!part || part === '.' || isAbsolute(part) || part === '..' || part.startsWith('..' + sep)) { + throw new Error('Invalid path in the copy inventory: ' + name); + } + const path = join(root, part); + if (!copyPathContains(root, await canonicalCopyPath(dirname(path)))) { + throw new Error('A directory points outside the copy: ' + path); + } + return path; +} + +export async function changeCopyFiles( + root: string, + prepare: (folder: string) => Promise<{ replace: readonly string[]; remove: readonly string[] }>, + recordChange: () => Promise, +): Promise { + const work = await mkdtemp(join(dirname(root), '.wto-copy-')); + const incoming = join(work, 'new'); + const backups = join(work, 'old'); + const changes: Array<{ target: string; saved: string | null; replaced: boolean }> = []; + let keepBackups = false; + try { + const { replace, remove } = await prepare(incoming); + for (const [paths, add] of [[replace, true], [remove, false]] as const) { + for (const path of paths) { + const target = await stagedPath(root, path); + const old = await fileInfo(target); + if (old?.isDirectory()) throw new Error('A game file is a directory: ' + target); + if (!old && !add) continue; + const entry = { target, saved: null as string | null, replaced: false }; + if (old) { + const saved = join(backups, path); + await mkdir(dirname(saved), { recursive: true }); + await rename(target, saved); + entry.saved = saved; + } + changes.push(entry); + if (add) { + await mkdir(dirname(target), { recursive: true }); + await rename(join(incoming, path), target); + entry.replaced = true; + } + } + } + return await recordChange(); + } catch (error) { + for (const { target, saved, replaced } of changes.reverse()) { + try { + if (replaced) await rm(target, { force: true }); + if (saved) await rename(saved, target); + } catch (rollbackError) { + keepBackups = true; + console.error('[copies] could not restore a file, recovery folder:', work, target, rollbackError); + } + } + throw error; + } finally { + if (!keepBackups && relative(dirname(root), dirname(work)) === '') { + await rm(work, { recursive: true, force: true }).catch((error) => console.warn('[copies] could not clear temporary files:', work, error)); + } + } +} diff --git a/apps/launcher/src/main/services/copies/copy-maintenance.ts b/apps/launcher/src/main/services/copies/copy-maintenance.ts new file mode 100644 index 0000000..04c0813 --- /dev/null +++ b/apps/launcher/src/main/services/copies/copy-maintenance.ts @@ -0,0 +1,267 @@ +import { createHash } from 'node:crypto'; +import { createReadStream } from 'node:fs'; +import { copyFile, mkdir, readdir, rm } from 'node:fs/promises'; +import { dirname, isAbsolute, join, normalize, parse, relative } from 'node:path'; +import { app } from 'electron'; +import { compareVersions, GAME_FILES, isInSteamLibrary } from '@wto/patcher'; +import { AppError } from '@shared/errors.ts'; +import type { Copies, GameFolderInspection, InstallRecord } from '@shared/schemas/install.ts'; +import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts'; +import { inspectGameFolder } from '../game-folder/inspect-game-folder.ts'; +import { copyPlannedFiles, planCopy, type CopyPlan } from '../install/copy-game.ts'; +import { installationInProgress } from '../install/install-game.ts'; +import { canonicalCopyPath, copyPathContains, listCopies, removeCopyRecord, updateCopyRecord } from '../install/install-record.ts'; +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 { changeCopyFiles, fileInfo, stagedPath } from './change-copy-files.ts'; + +let current: { stop: AbortController; interruptible: boolean } | null = null; + +export function maintenanceInProgress(): boolean { + return current !== null; +} + +export function cancelMaintenance(): void { + if (current?.interruptible) current.stop.abort(); +} + +export async function maintenanceInfo(id: string): Promise { + const record = await requireCopy(id); + const source = await readSource(record); + return { sourceVersion: source?.version ?? null, updateAvailable: isNewer(source, record.gameVersion) }; +} + +export async function maintainCopy( + request: MaintenanceRequest, + publish: (progress: MaintenanceProgress) => void, +): Promise { + if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy'); + const job = { stop: new AbortController(), interruptible: request.operation === 'update' }; + current = job; + const signal = job.stop.signal; + const report = (phase: MaintenanceProgress['phase'], doneBytes = 0, totalBytes = 0): void => { + if (phase === 'applying') job.interruptible = false; + publish({ id: request.id, operation: request.operation, phase, doneBytes, totalBytes }); + }; + report('checking'); + + try { + const record = await requireCopy(request.id); + const root = await checkedRoot(record); + if (await gameProcessRunning(signal) || await labServerUses(root)) throw new AppError('maintenance_busy'); + signal.throwIfAborted(); + + switch (request.operation) { + case 'check': + return await recordCheck(record, record.stockBackupPath); + case 'repair': + return await repair(record, root, () => report('applying')); + case 'update': + return await updateFromSource(record, root, signal, report); + case 'delete': + report('applying'); + return await remove(record, root, request.deleteData); + } + } catch (error) { + if (signal.aborted) throw new AppError('maintenance_cancelled'); + if (error instanceof AppError) throw error; + console.error('[copies] maintenance failed:', request.operation, error); + throw new AppError('maintenance_failed'); + } finally { + current = null; + } +} + +async function requireCopy(id: string): Promise { + const record = (await listCopies()).copies.find((copy) => copy.id === id); + if (!record) throw new AppError('copy_not_found'); + return record; +} + +async function readSource(record: InstallRecord): Promise { + if (!record.sourcePath) return null; + try { + const game = await inspectGameFolder(record.sourcePath); + return game.missingFiles.length > 0 ? null : game; + } catch (error) { + if (error instanceof AppError) return null; + throw error; + } +} + +function isNewer(source: GameFolderInspection | null, version: string | null): boolean { + return !!source?.version && !!version && compareVersions(source.version, version) > 0; +} + +async function checkedRoot(record: InstallRecord): Promise { + const root = await safeFolder(record.copyPath); + const backup = await canonicalCopyPath(record.stockBackupPath); + if (relative(join(root, STOCK_BACKUP_FOLDER), backup) !== '') throw new AppError('maintenance_location'); + if (record.sourcePath) { + const source = await canonicalCopyPath(record.sourcePath); + if (copyPathContains(source, root) || copyPathContains(root, source)) throw new AppError('maintenance_location'); + } + return root; +} + +async function safeFolder(path: string): Promise { + const root = await canonicalCopyPath(path); + if (!isAbsolute(path) || root === parse(root).root || isInSteamLibrary(root) || + copyPathContains(root, await canonicalCopyPath(app.getAppPath())) || + copyPathContains(root, await canonicalCopyPath(app.getPath('userData')))) { + throw new AppError('maintenance_location'); + } + if ((await fileInfo(path))?.isSymbolicLink()) throw new AppError('maintenance_location'); + return root; +} + +async function labServerUses(root: string): Promise { + const lab = await readInstalledLab().catch(() => null); + if (!lab || relative(lab.copyPath, root) !== '') return false; + try { + const response = await fetch(labStatusUrl(lab.port), { signal: AbortSignal.timeout(800) }); + return response.ok && (await response.json() as { app?: string }).app === 'wto-server'; + } catch { + return false; + } +} + +async function recordCheck(record: InstallRecord, folder: string): Promise { + const check = await checkPatches(folder, record.dataPath); + return updateCopyRecord(record.id, (copy) => ({ + ...copy, unavailablePatches: check.unavailable, lastCheckedAt: new Date().toISOString(), + })); +} + +async function repair(record: InstallRecord, root: string, applying: () => void): Promise { + return changeCopyFiles(root, async (incoming) => { + const files = Object.values(GAME_FILES); + for (const file of files) await stageBackup(record.stockBackupPath, file, join(incoming, file)); + applying(); + return { replace: files, remove: [] }; + }, listCopies); +} + +type Report = (phase: MaintenanceProgress['phase'], doneBytes?: number, totalBytes?: number) => void; + +async function updateFromSource(record: InstallRecord, root: string, signal: AbortSignal, report: Report): Promise { + const game = await readSource(record); + if (!game || !isNewer(game, record.gameVersion)) throw new AppError('maintenance_no_update'); + + const dataPath = await canonicalCopyPath(record.dataPath); + const plan = await planCopy(game.path); + const inventory = plan.files.map((entry) => entry.relativePath); + const found = new Set(inventory.map(key)); + const remove = (record.sourceFiles ?? []).filter((name) => !found.has(key(name))); + const changed: CopyPlan['files'][number][] = []; + for (const file of plan.files) { + signal.throwIfAborted(); + const target = await scopedInstallFile(dataPath, root, file.relativePath); + const old = await fileInfo(target); + if (!old?.isFile() || old.size !== file.bytes) { + changed.push(file); + } else if (Math.trunc(old.mtimeMs) !== Math.trunc(file.modifiedAt)) { + const [targetHash, sourceHash] = await Promise.all([ + fileHash(target, signal), fileHash(join(game.path, file.relativePath), signal), + ]); + if (targetHash !== sourceHash) changed.push(file); + } + } + for (const file of remove) await scopedInstallFile(dataPath, root, file); + + signal.throwIfAborted(); + const check = await checkPatches(game.path, record.dataPath); + signal.throwIfAborted(); + const copy: CopyPlan = { + files: changed, + folders: [...new Set(changed.map(({ relativePath }) => dirname(relativePath)))], + totalBytes: changed.reduce((total, file) => total + file.bytes, 0), + }; + return changeCopyFiles(root, async (incoming) => { + report('copying', 0, copy.totalBytes); + let lastReport = 0; + await copyPlannedFiles(game.path, incoming, copy, signal, ({ doneBytes }) => { + if (doneBytes === copy.totalBytes || Date.now() - lastReport >= 250) { + lastReport = Date.now(); + report('copying', doneBytes, copy.totalBytes); + } + }); + const stockFiles = Object.values(GAME_FILES).map((file) => join(STOCK_BACKUP_FOLDER, file)); + for (const file of Object.values(GAME_FILES)) { + signal.throwIfAborted(); + await stageBackup(game.path, file, join(incoming, STOCK_BACKUP_FOLDER, file)); + } + for (const file of plan.files) { + signal.throwIfAborted(); + const info = await fileInfo(join(game.path, file.relativePath)); + if (!info?.isFile() || info.size !== file.bytes || info.mtimeMs !== file.modifiedAt) { + throw new AppError('maintenance_source_changed'); + } + } + signal.throwIfAborted(); + report('applying', copy.totalBytes, copy.totalBytes); + return { replace: [...changed.map(({ relativePath }) => relativePath), ...stockFiles], remove }; + }, () => updateCopyRecord(record.id, (latest) => ({ + ...latest, gameVersion: game.version, unavailablePatches: check.unavailable, + lastCheckedAt: new Date().toISOString(), sourceFiles: inventory, + }))); +} + +function key(path: string): string { + const name = normalize(path); + return process.platform === 'win32' ? name.toLowerCase() : name; +} + +async function scopedInstallFile(dataPath: string, root: string, name: string): Promise { + const target = await stagedPath(root, name); + if (copyPathContains(join(root, dirname(STOCK_BACKUP_FOLDER)), target) || + copyPathContains(dataPath, target)) { + throw new AppError('maintenance_location'); + } + return target; +} + +async function fileHash(path: string, signal: AbortSignal): Promise { + const hash = createHash('sha256'); + for await (const bytes of createReadStream(path, { signal })) hash.update(bytes as Buffer); + return hash.digest('hex'); +} + +async function stageBackup(folder: string, file: string, target: string): Promise { + await mkdir(dirname(target), { recursive: true }); + const source = join(folder, file); + if (!(await fileInfo(source))?.isFile()) throw new AppError('maintenance_location'); + await copyFile(source, target); +} + +async function remove(record: InstallRecord, root: string, deleteData: boolean): Promise { + const data = deleteData ? await safeFolder(record.dataPath) : await canonicalCopyPath(record.dataPath); + const source = record.sourcePath ? await canonicalCopyPath(record.sourcePath) : null; + if (deleteData && ((source && (copyPathContains(data, source) || copyPathContains(source, data))) || + (relative(data, root) !== '' && copyPathContains(data, root)))) { + throw new AppError('maintenance_location'); + } + if (!deleteData && copyPathContains(root, data)) { + await removeExcept(root, data); + } else { + await rm(root, { recursive: true, force: true }); + } + if (deleteData && !copyPathContains(root, data)) await rm(data, { recursive: true, force: true }); + return removeCopyRecord(record.id); +} + +/** Keep the data folder in place when it was chosen inside this copy. */ +async function removeExcept(folder: string, kept: string): Promise { + if (relative(folder, kept) === '' || !(await fileInfo(folder))) return; + for (const entry of await readdir(folder, { withFileTypes: true })) { + const path = join(folder, entry.name); + if (copyPathContains(path, kept)) { + if (!entry.isDirectory()) throw new AppError('maintenance_location'); + await removeExcept(path, kept); + } else { + await rm(path, { recursive: true, force: true }); + } + } +} diff --git a/apps/launcher/src/main/services/install/copy-game.ts b/apps/launcher/src/main/services/install/copy-game.ts index e159aea..7d5eb3f 100644 --- a/apps/launcher/src/main/services/install/copy-game.ts +++ b/apps/launcher/src/main/services/install/copy-game.ts @@ -1,5 +1,5 @@ import { createReadStream, createWriteStream } from 'node:fs'; -import { lstat, mkdir, readdir, rm } from 'node:fs/promises'; +import { lstat, mkdir, readdir, rm, utimes } from 'node:fs/promises'; import { join, relative } from 'node:path'; import { Transform } from 'node:stream'; import { pipeline } from 'node:stream/promises'; @@ -20,6 +20,7 @@ const PLAYER_DATA_FOLDERS = new Set(['.game_logs', 'cache', 'replays', 'screensh interface CopyEntry { readonly relativePath: string; readonly bytes: number; + readonly modifiedAt: number; } export interface CopyPlan { @@ -48,9 +49,9 @@ export async function planCopy(source: string): Promise { folders.push(relative(source, path)); pending.push(path); } else if (entry.isFile()) { - const bytes = (await lstat(path)).size; - files.push({ relativePath: relative(source, path), bytes }); - totalBytes += bytes; + const { size, mtimeMs } = await lstat(path); + files.push({ relativePath: relative(source, path), bytes: size, modifiedAt: mtimeMs }); + totalBytes += size; } } } @@ -100,6 +101,8 @@ export async function copyPlannedFiles( createWriteStream(join(target, file.relativePath), { flags: 'wx' }), { signal: stopSignal }, ); + const modified = new Date(file.modifiedAt); + await utimes(join(target, file.relativePath), modified, modified); doneFiles += 1; onProgress({ doneBytes, doneFiles }); } diff --git a/apps/launcher/src/main/services/install/install-game.ts b/apps/launcher/src/main/services/install/install-game.ts index a9cd4d3..3ff3783 100644 --- a/apps/launcher/src/main/services/install/install-game.ts +++ b/apps/launcher/src/main/services/install/install-game.ts @@ -25,6 +25,10 @@ const PROGRESS_INTERVAL_MS = 250; let running: AbortController | null = null; +export function installationInProgress(): boolean { + return running !== null; +} + export async function installGame(request: InstallRequest, onProgress: (progress: InstallProgress) => void): Promise { if (running) throw new AppError('install_busy'); const controller = new AbortController(); @@ -82,7 +86,9 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr if (check.unavailable.length && !request.missingFeaturesAccepted) throw new AppError('missing_features_not_accepted'); signal.throwIfAborted(); - if (request.method === 'copy') await copyGame(request.sourcePath, copyPath, target!.freeBytes, signal, report); + const sourceFiles = request.method === 'copy' + ? await copyGame(request.sourcePath, copyPath, target!.freeBytes, signal, report) + : undefined; report({ phase: 'backing-up', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); const stockBackup = await backUpStockFiles(copyPath); @@ -99,6 +105,8 @@ async function install(request: InstallRequest, signal: AbortSignal, report: (pr gameVersion: game.version, unavailablePatches: check.unavailable, installedAt: new Date().toISOString(), + lastCheckedAt: new Date().toISOString(), + ...(sourceFiles ? { sourceFiles } : {}), }; await writeInstallRecord(record); return record; @@ -110,7 +118,7 @@ async function copyGame( freeBytes: number | null, signal: AbortSignal, report: (progress: InstallProgress) => void, -): Promise { +): Promise { report({ phase: 'measuring', doneBytes: 0, totalBytes: 0, doneFiles: 0, totalFiles: 0 }); const plan = await planCopy(source); if (freeBytes !== null && freeBytes < plan.totalBytes + SPARE_BYTES) { @@ -121,6 +129,7 @@ async function copyGame( report({ phase: 'copying', doneBytes: 0, doneFiles: 0, ...totals }); try { await copyPlannedFiles(source, target, plan, signal, (done) => report({ phase: 'copying', ...done, ...totals })); + return plan.files.map((file) => file.relativePath); } catch (error) { await removeInterruptedCopy(target, targetExisted).catch((cleanup) => console.error('[install] removing the interrupted copy failed:', cleanup)); if (signal.aborted) throw new AppError('install_cancelled'); diff --git a/apps/launcher/src/main/services/install/install-record.ts b/apps/launcher/src/main/services/install/install-record.ts index 3321f73..9164dc2 100644 --- a/apps/launcher/src/main/services/install/install-record.ts +++ b/apps/launcher/src/main/services/install/install-record.ts @@ -56,13 +56,24 @@ export function setCurrentCopy(id: string): Promise { }); } -export function renameCopy(id: string, name: string): Promise { +export function updateCopyRecord(id: string, change: (record: InstallRecord) => InstallRecord): Promise { return changeRegistry((registry) => { - if (!registry.copies.some((copy) => copy.id === id)) throw new AppError('copy_not_found'); - return { ...registry, copies: registry.copies.map((copy) => copy.id === id ? { ...copy, name } : copy) }; + if (!registry.copies.some((record) => record.id === id)) throw new AppError('copy_not_found'); + return { ...registry, copies: registry.copies.map((record) => record.id === id ? change(record) : record) }; }); } +export function removeCopyRecord(id: string): Promise { + return changeRegistry((registry) => { + const copies = registry.copies.filter((record) => record.id !== id); + return { ...registry, copies, current: registry.current === id ? copies[0]?.id ?? null : registry.current }; + }); +} + +export function renameCopy(id: string, name: string): Promise { + return updateCopyRecord(id, (record) => ({ ...record, name })); +} + /** Serialize writes so switching, renaming and completing an installation preserve each other. */ function changeRegistry(change: (registry: Copies) => Promise | Copies): Promise { const operation = pending.then(async () => { @@ -81,30 +92,31 @@ function changeRegistry(change: (registry: Copies) => Promise | Copies): } async function requireUniquePaths(registry: Copies, id: string, copyPath: string, dataPath: string): Promise { - const paths = await Promise.all([canonical(copyPath), canonical(dataPath)]); + const paths = await Promise.all([canonicalCopyPath(copyPath), canonicalCopyPath(dataPath)]); for (const existing of registry.copies) { - const used = await Promise.all([canonical(existing.copyPath), canonical(existing.dataPath)]); + const used = await Promise.all([canonicalCopyPath(existing.copyPath), canonicalCopyPath(existing.dataPath)]); if (id === existing.id || paths.some((path) => used.some((other) => overlaps(path, other)))) { throw new AppError('copy_location_in_use'); } } } +export function copyPathContains(parent: string, child: string): boolean { + const remainder = relative(parent, child); + return !isAbsolute(remainder) && remainder !== '..' && !remainder.startsWith('..' + sep); +} + function overlaps(left: string, right: string): boolean { - function contains(parent: string, child: string): boolean { - const remainder = relative(parent, child); - return !isAbsolute(remainder) && remainder !== '..' && !remainder.startsWith('..' + sep); - } - return contains(left, right) || contains(right, left); + return copyPathContains(left, right) || copyPathContains(right, left); } /** Resolve junctions in a path even when its final folders have yet to be made. */ -async function canonical(path: string): Promise { +export async function canonicalCopyPath(path: string): Promise { const absolute = resolve(path); try { return await realpath(absolute); } catch { const parent = dirname(absolute); - return parent === absolute ? absolute : join(await canonical(parent), relative(parent, absolute)); + return parent === absolute ? absolute : join(await canonicalCopyPath(parent), relative(parent, absolute)); } } diff --git a/apps/launcher/src/main/services/launch/launch-controller.ts b/apps/launcher/src/main/services/launch/launch-controller.ts index 6421849..1f4aa2e 100644 --- a/apps/launcher/src/main/services/launch/launch-controller.ts +++ b/apps/launcher/src/main/services/launch/launch-controller.ts @@ -25,6 +25,16 @@ interface LaunchJob { let active: LaunchJob | null = null; let state: LaunchState = { phase: 'ready' }; +export function launchInProgress(): boolean { + return active !== null; +} + +export async function gameProcessRunning(signal: AbortSignal): Promise { + if (process.platform !== 'win32') return false; + const games = await execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal }); + return /^"aces\.exe",/im.test(games.stdout); +} + export function getLaunchState(): LaunchState { return state; } @@ -107,11 +117,11 @@ async function launch(job: LaunchJob): Promise { 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 }), + gameProcessRunning(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'); + if (games) throw new AppError('launch_game_running'); await checkPort(lab.port); signal.throwIfAborted(); update(job, { phase: 'building', port: lab.port }); diff --git a/apps/launcher/src/renderer/src/App.tsx b/apps/launcher/src/renderer/src/App.tsx index ea5fc59..23f23bf 100644 --- a/apps/launcher/src/renderer/src/App.tsx +++ b/apps/launcher/src/renderer/src/App.tsx @@ -8,6 +8,7 @@ import { Sheet } from './components/Sheet.tsx'; import { applyLanguage, resolveLanguage } from './i18n/index.ts'; import { ipcInvoke, ipcOn } from './ipc.ts'; import { AboutPage } from './pages/about/AboutPage.tsx'; +import { CopyMaintenance } from './pages/copies/CopyMaintenance.tsx'; import { CopyList } from './pages/copies/CopyList.tsx'; import { CopySummary } from './pages/copies/CopySummary.tsx'; import { FeatureStatus } from './pages/copies/FeatureStatus.tsx'; @@ -145,6 +146,9 @@ export function App({ info, initialSettings, initialCopies }: AppProps) { bar: home, }; } + if (route.copies === 'maintain') { + return { side, main: , bar: home }; + } const main = route.copies === 'features' ? : go({ page: 'copies', section: 'features' })} onError={report} />; diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 607c3a1..9e081a8 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -166,11 +166,43 @@ "sections": { "list": "All copies", "summary": "Copy details", - "features": "Feature status" + "features": "Feature status", + "maintain": "Maintenance" }, "add": "Add a copy", "list": { "current": "Current", "select": "Set as current" }, "none": "The offline edition is not installed yet.", + "maintenance": { + "update": "Update from official installation", + "updateAction": "Update copy", + "newVersion": "Version {{version}} is available from the installation source.", + "currentVersion": "Installation source version {{version}}", + "noSource": "Installation source unavailable", + "check": "Recheck patches", + "checkHint": "Check the original file backup.", + "lastCheck": "Last checked {{date}}", + "repair": "Repair copy", + "repairAction": "Repair", + "repairHint": "Restore the original files from the backup. Game files will be generated again at launch.", + "delete": "Delete copy", + "deleteAction": "Delete…", + "deleteHint": "The data folder is kept by default.", + "deleteLocation": "Delete the game copy at {{path}}?", + "deleteData": "Also delete the data folder at {{path}}", + "confirm": "Confirm deletion", + "phase": { + "checking": "Checking the copy", + "copying": "Copying changed files", + "applying": "Applying changes" + }, + "result": { + "check": "Patch check complete.", + "repair": "Original files restored.", + "update": "Copy updated.", + "delete": "Copy deleted.", + "cancelled": "Update cancelled." + } + }, "summary": { "name": "Copy name", "rename": "Rename", @@ -334,6 +366,12 @@ "copy_not_found": "The selected copy is no longer available.", "copies_write_failed": "The copy registry could not be saved.", "copy_location_in_use": "The copy or data location overlaps an existing copy.", + "maintenance_busy": "Maintenance requires the game, local server and other copy operations to be stopped.", + "maintenance_location": "The operation would affect files outside the registered copy or data folder.", + "maintenance_no_update": "A newer version is unavailable at the installation source.", + "maintenance_cancelled": "The copy update was cancelled.", + "maintenance_failed": "Copy maintenance failed. See the launcher log.", + "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_lab_required": "Enable developer mode to launch through the isolated lab.", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index b04568b..19b89d5 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -166,11 +166,43 @@ "sections": { "list": "全部副本", "summary": "副本详情", - "features": "功能状态" + "features": "功能状态", + "maintain": "维护" }, "add": "添加副本", "list": { "current": "当前", "select": "设为当前" }, "none": "尚未安装离线版。", + "maintenance": { + "update": "从正版更新", + "updateAction": "更新副本", + "newVersion": "安装来源已更新至 {{version}}。", + "currentVersion": "安装来源版本 {{version}}", + "noSource": "安装来源不可用", + "check": "重新检查补丁", + "checkHint": "核对原版文件备份。", + "lastCheck": "上次检查 {{date}}", + "repair": "修复副本", + "repairAction": "修复", + "repairHint": "从原版文件备份还原文件。下次启动时重新生成游戏文件。", + "delete": "删除副本", + "deleteAction": "删除…", + "deleteHint": "默认保留数据目录。", + "deleteLocation": "确认删除 {{path}} 中的游戏副本?", + "deleteData": "同时删除 {{path}} 中的数据", + "confirm": "确认删除", + "phase": { + "checking": "正在检查副本", + "copying": "正在复制有变化的文件", + "applying": "正在应用更改" + }, + "result": { + "check": "补丁检查已完成。", + "repair": "原版文件已还原。", + "update": "副本已更新。", + "delete": "副本已删除。", + "cancelled": "更新已取消。" + } + }, "summary": { "name": "副本名称", "rename": "重命名", @@ -334,6 +366,12 @@ "copy_not_found": "所选副本已不可用。", "copies_write_failed": "无法保存副本记录。", "copy_location_in_use": "副本位置或数据目录与已有副本重叠。", + "maintenance_busy": "维护前需结束游戏、本地服务器和其他副本操作。", + "maintenance_location": "操作会影响登记的副本或数据目录之外的文件。", + "maintenance_no_update": "安装来源没有可用的新版本。", + "maintenance_cancelled": "副本更新已取消。", + "maintenance_failed": "副本维护失败。请查看启动器日志。", + "maintenance_source_changed": "安装来源在更新过程中发生变化。请在正版更新完成后重试。", "launch_no_copy": "启动前需要安装游戏副本。", "launch_busy": "启动流程正在运行。", "launch_lab_required": "请启用开发模式以通过隔离实验副本启动。", diff --git a/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx new file mode 100644 index 0000000..cf6378d --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/copies/CopyMaintenance.tsx @@ -0,0 +1,113 @@ +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import type { InstallRecord } from '@shared/schemas/install.ts'; +import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts'; +import { ProgressBar } from '../../components/ProgressBar.tsx'; +import { Row } from '../../components/Row.tsx'; +import { Sheet } from '../../components/Sheet.tsx'; +import { formatBytes } from '../../format.ts'; +import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts'; + +interface CopyMaintenanceProps { + readonly record: InstallRecord; + readonly onError: (error: unknown) => void; +} + +type Operation = MaintenanceRequest['operation']; + +export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) { + const { t, i18n } = useTranslation(); + const [info, setInfo] = useState(null); + const [working, setWorking] = useState(null); + const [progress, setProgress] = useState(null); + const [confirming, setConfirming] = useState(false); + const [deleteData, setDeleteData] = useState(false); + const [result, setResult] = useState(null); + + useEffect(() => { + let mounted = true; + ipcInvoke('copies:maintenanceInfo', { id: record.id }).then((value) => { + if (mounted) setInfo(value); + }).catch(onError); + return () => { mounted = false; }; + }, [record.id, record.gameVersion, onError]); + + useEffect(() => ipcOn('event:copy-maintenance', (event) => { + if (event.id === record.id) setProgress(event); + }), [record.id]); + + const run = (operation: Operation): void => { + setResult(null); + setWorking(operation); + setProgress(null); + ipcInvoke('copies:maintain', { id: record.id, operation, deleteData: operation === 'delete' && deleteData }) + .then(() => { + setResult(operation); + setConfirming(false); + }) + .catch((error: unknown) => { + if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') setResult('cancelled'); + else onError(error); + }) + .finally(() => setWorking(null)); + }; + + return ( + + + + + + + + + + + + + + {confirming && ( +
+

{t('copies.maintenance.deleteLocation', { path: record.copyPath })}

+ +
+ + +
+
+ )} + {working && ( +
+

{t(`copies.maintenance.phase.${progress?.phase ?? 'checking'}`)}

+ + {progress?.totalBytes ?

{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}

: null} + {working === 'update' && progress?.phase !== 'applying' && ( + + )} +
+ )} + {result &&

{t(`copies.maintenance.result.${result}`)}

} +
+ ); +} diff --git a/apps/launcher/src/renderer/src/shell/navigation.ts b/apps/launcher/src/renderer/src/shell/navigation.ts index 550a6a9..f6b11f8 100644 --- a/apps/launcher/src/renderer/src/shell/navigation.ts +++ b/apps/launcher/src/renderer/src/shell/navigation.ts @@ -6,7 +6,7 @@ export const PAGES = ['home', 'copies', 'settings', 'about'] as const; export type PageId = (typeof PAGES)[number]; -export const COPY_SECTIONS = ['list', 'summary', 'features'] as const; +export const COPY_SECTIONS = ['list', 'summary', 'features', 'maintain'] as const; export type CopySection = (typeof COPY_SECTIONS)[number]; export const SETTINGS_SECTIONS = ['general', 'launch', 'diag', 'dev'] as const; diff --git a/apps/launcher/src/renderer/src/styles/pages.css b/apps/launcher/src/renderer/src/styles/pages.css index 41709f6..f37315c 100644 --- a/apps/launcher/src/renderer/src/styles/pages.css +++ b/apps/launcher/src/renderer/src/styles/pages.css @@ -285,6 +285,24 @@ min-height: 84px; } +.maintenance-confirm, +.maintenance-progress { + margin-top: 14px; + padding: 12px; + border: 1px solid var(--line); + overflow-wrap: anywhere; +} + +.maintenance-confirm p, +.maintenance-progress p { + margin: 0 0 8px; +} + +.maintenance-confirm .copy-list-actions, +.maintenance-progress button { + margin-top: 10px; +} + /* ===== About ===== */ .about-head { display: flex; diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index 3b872bf..6852d1d 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -18,6 +18,12 @@ export const APP_ERROR_CODES = [ 'diagnostics_export_failed', 'copy_not_found', 'copies_write_failed', + 'maintenance_busy', + 'maintenance_location', + 'maintenance_no_update', + 'maintenance_cancelled', + 'maintenance_failed', + 'maintenance_source_changed', 'copy_location_in_use', 'launch_no_copy', 'launch_busy', diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index 888ec57..4eb0c16 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -14,6 +14,7 @@ import { TargetFolderInspectionSchema, } from '../schemas/install.ts'; import { LabInfoSchema, LaunchStateSchema } from '../schemas/launch.ts'; +import { MaintenanceInfoSchema, MaintenanceProgressSchema, MaintenanceRequestSchema } from '../schemas/maintenance.ts'; import { SettingsPatchSchema, SettingsSchema } from '../schemas/settings.ts'; /** @@ -114,6 +115,18 @@ export const ipcContract = { input: z.object({ id: CopyIdSchema, name: CopyNameSchema }), output: CopiesSchema, }, + 'copies:maintenanceInfo': { + input: z.object({ id: CopyIdSchema }), + output: MaintenanceInfoSchema, + }, + 'copies:maintain': { + input: MaintenanceRequestSchema, + output: CopiesSchema, + }, + 'copies:cancelMaintenance': { + input: z.void(), + output: z.void(), + }, 'launch:getState': { input: z.void(), output: LaunchStateSchema, @@ -157,6 +170,7 @@ export const ipcEvents = { 'event:install-progress': InstallProgressSchema, 'event:launch-state': LaunchStateSchema, 'event:copies-changed': CopiesSchema, + 'event:copy-maintenance': MaintenanceProgressSchema, } as const; export type IpcChannel = keyof typeof ipcContract; diff --git a/apps/launcher/src/shared/schemas/install.ts b/apps/launcher/src/shared/schemas/install.ts index a9425b4..9001df7 100644 --- a/apps/launcher/src/shared/schemas/install.ts +++ b/apps/launcher/src/shared/schemas/install.ts @@ -133,6 +133,9 @@ export const InstallRecordSchema = z.object({ /** Patches that did not fit when the copy was installed; their features are missing. */ unavailablePatches: z.array(UnavailablePatchSchema), installedAt: z.string(), + lastCheckedAt: z.string().optional(), + /** Relative paths read from the installation source during the last copy or update. */ + sourceFiles: z.array(z.string().min(1)).optional(), }); export type InstallRecord = z.output; diff --git a/apps/launcher/src/shared/schemas/maintenance.ts b/apps/launcher/src/shared/schemas/maintenance.ts new file mode 100644 index 0000000..9d6b977 --- /dev/null +++ b/apps/launcher/src/shared/schemas/maintenance.ts @@ -0,0 +1,24 @@ +import { z } from 'zod'; +import { CopyIdSchema } from './install.ts'; + +export const MaintenanceOperationSchema = z.enum(['check', 'repair', 'update', 'delete']); +export const MaintenanceRequestSchema = z.object({ + id: CopyIdSchema, + operation: MaintenanceOperationSchema, + deleteData: z.boolean().default(false), +}); +export const MaintenanceInfoSchema = z.object({ + sourceVersion: z.string().nullable(), + updateAvailable: z.boolean(), +}); +export const MaintenanceProgressSchema = z.object({ + id: CopyIdSchema, + operation: MaintenanceOperationSchema, + phase: z.enum(['checking', 'copying', 'applying']), + doneBytes: z.number().nonnegative(), + totalBytes: z.number().nonnegative(), +}); + +export type MaintenanceRequest = z.output; +export type MaintenanceInfo = z.output; +export type MaintenanceProgress = z.output;