From d633280e239ce48315ccb5ff53092883f5024410 Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:45:49 +0800 Subject: [PATCH] feat(launcher): add logging and diagnostics export --- apps/launcher/src/main/index.ts | 2 + apps/launcher/src/main/ipc/handlers.ts | 4 + .../main/services/diagnostics/diagnostics.ts | 86 +++++++++++++++++++ .../main/services/diagnostics/launcher-log.ts | 55 ++++++++++++ apps/launcher/src/renderer/src/App.tsx | 5 +- .../src/renderer/src/i18n/locales/en.json | 14 ++- .../src/renderer/src/i18n/locales/zh-CN.json | 14 ++- .../pages/settings/DiagnosticsSettings.tsx | 44 ++++++++++ .../src/renderer/src/shell/navigation.ts | 2 +- apps/launcher/src/shared/errors.ts | 2 + apps/launcher/src/shared/ipc/contract.ts | 9 ++ 11 files changed, 233 insertions(+), 4 deletions(-) create mode 100644 apps/launcher/src/main/services/diagnostics/diagnostics.ts create mode 100644 apps/launcher/src/main/services/diagnostics/launcher-log.ts create mode 100644 apps/launcher/src/renderer/src/pages/settings/DiagnosticsSettings.tsx diff --git a/apps/launcher/src/main/index.ts b/apps/launcher/src/main/index.ts index cea8055..6e74d51 100644 --- a/apps/launcher/src/main/index.ts +++ b/apps/launcher/src/main/index.ts @@ -1,6 +1,7 @@ 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'; /** @@ -22,6 +23,7 @@ registerArtScheme(); if (!app.requestSingleInstanceLock()) { app.quit(); } else { + startLauncherLogging(); app.on('second-instance', () => showMainWindow()); app.on('window-all-closed', () => app.quit()); // A top-level await on whenReady deadlocks an ESM main entry on Windows. diff --git a/apps/launcher/src/main/ipc/handlers.ts b/apps/launcher/src/main/ipc/handlers.ts index bbc6876..b9b3dde 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 { 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'; import { inspectTargetFolder } from '../services/game-folder/inspect-target-folder.ts'; @@ -33,6 +34,9 @@ export function registerIpcHandlers(): void { if (failure) console.warn('[app] opening the folder failed:', path, failure); }); + handle('app:openLogsFolder', () => openLogsFolder()); + handle('app:exportDiagnostics', (_input, sender) => exportDiagnostics(BrowserWindow.fromWebContents(sender))); + handle('window:minimize', (_input, sender) => { BrowserWindow.fromWebContents(sender)?.minimize(); }); diff --git a/apps/launcher/src/main/services/diagnostics/diagnostics.ts b/apps/launcher/src/main/services/diagnostics/diagnostics.ts new file mode 100644 index 0000000..0d53a82 --- /dev/null +++ b/apps/launcher/src/main/services/diagnostics/diagnostics.ts @@ -0,0 +1,86 @@ +import { randomUUID } from 'node:crypto'; +import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { app, dialog, shell, type BrowserWindow } from 'electron'; +import { zipSync } from 'fflate'; +import { AppError } from '@shared/errors.ts'; +import { readInstallRecord } from '../install/install-record.ts'; +import { LAUNCHER_LOG_FILES, launcherLogFolder } from './launcher-log.ts'; + +type ArchiveFiles = Record; + +export async function openLogsFolder(): Promise { + const path = launcherLogFolder(); + try { + await mkdir(path, { recursive: true }); + const failure = await shell.openPath(path); + if (failure) throw new Error(failure); + } catch (error) { + console.warn('[diagnostics] opening the log folder failed:', error); + throw new AppError('logs_folder_open_failed'); + } +} + +export async function exportDiagnostics(window: BrowserWindow | null): Promise<{ path: string | null }> { + try { + const date = new Date().toISOString().slice(0, 10); + const options = { + defaultPath: `WTOffline-diagnostics-${date}.zip`, + filters: [{ name: 'ZIP', extensions: ['zip'] }], + }; + const result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options); + if (result.canceled || !result.filePath) return { path: null }; + + const files: ArchiveFiles = {}; + const userData = app.getPath('userData'); + await addFile(files, 'settings.json', join(userData, 'settings.json')); + await addFile(files, 'install.json', join(userData, 'install.json')); + const launcherLogs = launcherLogFolder(); + if ((await ifPresent(() => lstat(launcherLogs)))?.isDirectory()) { + for (const name of LAUNCHER_LOG_FILES) { + await addFile(files, `launcher-logs/${name}`, join(launcherLogs, name)); + } + } + const record = await readInstallRecord(); + if (record) await addServerLogs(files, record.dataPath); + + const temporary = `${result.filePath}.${randomUUID()}.tmp`; + try { + await writeFile(temporary, zipSync(files), { flag: 'wx' }); + await rename(temporary, result.filePath); + } catch (error) { + await rm(temporary, { force: true }).catch(() => undefined); + throw error; + } + return { path: result.filePath }; + } catch (error) { + console.error('[diagnostics] exporting the archive failed:', error); + throw new AppError('diagnostics_export_failed'); + } +} + +/** Include the server's request journals. Traffic bodies can contain player data. */ +async function addServerLogs(files: ArchiveFiles, dataPath: string): Promise { + const root = join(dataPath, 'logs'); + if (!(await ifPresent(() => lstat(root)))?.isDirectory()) return; + const sessions = await ifPresent(() => readdir(root, { withFileTypes: true })); + for (const session of sessions ?? []) { + if (!session.isDirectory() || !/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z$/.test(session.name)) continue; + const source = join(root, session.name, 'requests.jsonl'); + await addFile(files, `server-logs/${session.name}/requests.jsonl`, source); + } +} + +async function addFile(files: ArchiveFiles, entry: string, path: string): Promise { + if (!(await ifPresent(() => lstat(path)))?.isFile()) return; + const bytes = await ifPresent(() => readFile(path)); + if (bytes) files[entry] = bytes; +} + +async function ifPresent(operation: () => Promise): Promise { + try { + return await operation(); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } +} diff --git a/apps/launcher/src/main/services/diagnostics/launcher-log.ts b/apps/launcher/src/main/services/diagnostics/launcher-log.ts new file mode 100644 index 0000000..21f8943 --- /dev/null +++ b/apps/launcher/src/main/services/diagnostics/launcher-log.ts @@ -0,0 +1,55 @@ +import { Console } from 'node:console'; +import { appendFileSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { Writable } from 'node:stream'; +import { app } from 'electron'; + +export const LAUNCHER_LOG_FILES = [ + 'launcher.log', + 'launcher.1.log', + 'launcher.2.log', + 'launcher.3.log', + 'launcher.4.log', +] as const; + +export function launcherLogFolder(): string { + return join(app.getPath('userData'), 'logs'); +} + +/** Rotate after taking the single-instance lock and keep the original console destinations. */ +export function startLauncherLogging(): void { + const originalConsole = console; + const folder = launcherLogFolder(); + const active = join(folder, LAUNCHER_LOG_FILES[0]); + try { + mkdirSync(folder, { recursive: true }); + for (let index = LAUNCHER_LOG_FILES.length - 1; index > 0; index -= 1) { + const previous = join(folder, LAUNCHER_LOG_FILES[index - 1]!); + if (existsSync(previous)) renameSync(previous, join(folder, LAUNCHER_LOG_FILES[index]!)); + } + writeFileSync(active, '', { flag: 'wx' }); + } catch (error) { + originalConsole.error('[logs] opening the launcher log failed:', error); + return; + } + + let fileFailed = false; + const mirror = (destination: NodeJS.WriteStream, stream: string): Writable => new Writable({ + write(chunk: Buffer, _encoding, done) { + if (!fileFailed) { + try { + appendFileSync(active, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`); + } catch (error) { + fileFailed = true; + originalConsole.error('[logs] writing the launcher log failed:', error); + } + } + destination.write(chunk, done); + }, + }); + globalThis.console = new Console({ + stdout: mirror(process.stdout, 'stdout'), + stderr: mirror(process.stderr, 'stderr'), + }); + console.info(`WTOffline Launcher ${app.getVersion()} started.`); +} diff --git a/apps/launcher/src/renderer/src/App.tsx b/apps/launcher/src/renderer/src/App.tsx index b7a0a78..a0b5c3b 100644 --- a/apps/launcher/src/renderer/src/App.tsx +++ b/apps/launcher/src/renderer/src/App.tsx @@ -17,6 +17,7 @@ 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 { DiagnosticsSettings } from './pages/settings/DiagnosticsSettings.tsx'; import { GeneralSettings } from './pages/settings/GeneralSettings.tsx'; import { Background } from './shell/Background.tsx'; import { BottomBar } from './shell/BottomBar.tsx'; @@ -92,7 +93,9 @@ export function App({ info, initialSettings, initialRecord, defaultDataPath }: A case 'settings': return { side: t(`settings.sections.${section}`)} onSelect={(section) => go({ page: 'settings', section })} />, - main: , + main: route.settings === 'diag' + ? + : , bar: home, }; case 'copies': { diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 746b71c..b8a8378 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -198,7 +198,17 @@ }, "settings": { "sections": { - "general": "General" + "general": "General", + "diag": "Diagnostics" + }, + "diagnostics": { + "logs": "Logs", + "logsHint": "Logs recorded by the launcher", + "openLogs": "Open log folder", + "export": "Export diagnostics", + "exportHint": "Save logs, settings and the installation record to a ZIP file", + "save": "Export…", + "saved": "Diagnostics saved to {{path}}." }, "language": "Language", "languageHint": "Display language of the launcher" @@ -269,6 +279,8 @@ }, "errors": { "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.", "settings_write_failed": "The settings could not be saved.", "folder_unreadable": "The folder cannot be read: {{path}}", "not_a_game_folder": "The selected folder is not a War Thunder installation: {{path}}", diff --git a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json index d42f0c9..75f00d7 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -198,7 +198,17 @@ }, "settings": { "sections": { - "general": "常规" + "general": "常规", + "diag": "诊断" + }, + "diagnostics": { + "logs": "日志", + "logsHint": "启动器运行日志", + "openLogs": "打开日志文件夹", + "export": "导出诊断信息", + "exportHint": "导出包含日志、设置和安装记录的 ZIP 文件", + "save": "导出…", + "saved": "诊断信息已保存到 {{path}}。" }, "language": "语言", "languageHint": "启动器界面的显示语言" @@ -269,6 +279,8 @@ }, "errors": { "internal_error": "启动器内部错误。", + "logs_folder_open_failed": "无法打开启动器日志文件夹。", + "diagnostics_export_failed": "无法保存诊断信息。", "settings_write_failed": "无法保存设置。", "folder_unreadable": "无法读取文件夹:{{path}}", "not_a_game_folder": "所选文件夹不是战争雷霆的安装文件夹:{{path}}", diff --git a/apps/launcher/src/renderer/src/pages/settings/DiagnosticsSettings.tsx b/apps/launcher/src/renderer/src/pages/settings/DiagnosticsSettings.tsx new file mode 100644 index 0000000..e114f7a --- /dev/null +++ b/apps/launcher/src/renderer/src/pages/settings/DiagnosticsSettings.tsx @@ -0,0 +1,44 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Row } from '../../components/Row.tsx'; +import { Sheet } from '../../components/Sheet.tsx'; +import { ipcInvoke } from '../../ipc.ts'; + +interface DiagnosticsSettingsProps { + readonly onError: (error: unknown) => void; +} + +export function DiagnosticsSettings({ onError }: DiagnosticsSettingsProps) { + const { t } = useTranslation(); + const [exporting, setExporting] = useState(false); + const [savedPath, setSavedPath] = useState(null); + + async function save(): Promise { + setExporting(true); + setSavedPath(null); + try { + const result = await ipcInvoke('app:exportDiagnostics'); + setSavedPath(result.path); + } catch (error) { + onError(error); + } finally { + setExporting(false); + } + } + + return ( + + + + + + + + {savedPath &&

{t('settings.diagnostics.saved', { path: savedPath })}

} +
+ ); +} diff --git a/apps/launcher/src/renderer/src/shell/navigation.ts b/apps/launcher/src/renderer/src/shell/navigation.ts index a9845ab..7f2f1ff 100644 --- a/apps/launcher/src/renderer/src/shell/navigation.ts +++ b/apps/launcher/src/renderer/src/shell/navigation.ts @@ -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'] as const; +export const SETTINGS_SECTIONS = ['general', 'diag'] as const; export type SettingsSection = (typeof SETTINGS_SECTIONS)[number]; export interface Route { diff --git a/apps/launcher/src/shared/errors.ts b/apps/launcher/src/shared/errors.ts index bce029b..75c8d8e 100644 --- a/apps/launcher/src/shared/errors.ts +++ b/apps/launcher/src/shared/errors.ts @@ -14,6 +14,8 @@ export const APP_ERROR_CODES = [ 'internal_error', /** The launcher's own settings file could not be written. */ 'settings_write_failed', + 'logs_folder_open_failed', + 'diagnostics_export_failed', /** A folder the player chose does not exist or cannot be read (params: path). */ 'folder_unreadable', /** The chosen folder lacks the files of a War Thunder installation (params: path). */ diff --git a/apps/launcher/src/shared/ipc/contract.ts b/apps/launcher/src/shared/ipc/contract.ts index 68392cd..9bd4309 100644 --- a/apps/launcher/src/shared/ipc/contract.ts +++ b/apps/launcher/src/shared/ipc/contract.ts @@ -42,6 +42,15 @@ export const ipcContract = { input: z.object({ path: z.string().min(1) }), output: z.void(), }, + 'app:openLogsFolder': { + input: z.void(), + output: z.void(), + }, + 'app:exportDiagnostics': { + input: z.void(), + /** The saved archive, or null when the player cancelled. */ + output: z.object({ path: z.string().nullable() }), + }, 'dialog:pickFolder': { /** The dialog title, already translated by the window. */ input: z.object({ title: z.string().optional() }),