diff --git a/.github/release-notes/v0.1.2.md b/.github/release-notes/v0.1.2.md index 966c215..02c67bd 100644 --- a/.github/release-notes/v0.1.2.md +++ b/.github/release-notes/v0.1.2.md @@ -6,6 +6,7 @@ - **省空间复制改为跨版本规则。** 取消原先绑定单一版本号(`2.61.0.43`)与 8 MiB 体积门槛的静态哈希清单,改为基于只读资源规则自动共用 `content/` 与 `content.hq/` 下的 `.dxp.bin` 和 `.grp` 资源包;小版本更新后无需等待新清单即可继续省空间安装或转换,且同卷省空间客户端执行「从在线版更新」时会保持或重建硬链接,不再拆分为完整复制。 - **修复维护页「从在线版更新」误报路径越界。** 扫描安装来源时排除顶层残留的 `wtoffline` 目录;安装向导第 3 步与后台同步拦截将数据目录设为客户端目录或其父目录的配置,并解除旧安装把数据目录放在客户端父目录时的误报;所有路径安全校验失败均在启动器日志中记录具体原因与路径以便排查。 +- **「关于」页快速导出日志与关闭日志开关。** 在「关于」页新增「保存日志 ZIP…」快捷按钮(导出内容同时纳入最新一份内置浏览器 `-browser.log`,仍不含玩家存档),并在「设置 → 诊断」新增「生成运行日志」开关,允许关闭启动器日志、本地服务器流量日志及 `wto_ws.log` 的磁盘写入。 ### 客户端兼容性 @@ -19,6 +20,7 @@ - **Version-independent space-saving copies.** Replaced the single-version (`2.61.0.43`) SHA-256 manifest and 8 MiB cutoff with declarative read-only asset rules covering `.dxp.bin` and `.grp` archives under `content/` and `content.hq/`. Space-saving installs and conversions now keep working across minor updates, and updating a same-volume space-saving client preserves or recreates hard links instead of detaching them into full copies. - **Fix false `maintenance_location` errors when updating.** Ignore stray top-level `wtoffline` folders when scanning a stock source, prevent picking a data folder that equals or contains the client folder during installation (with inline Step 3 validation), stop blocking updates when an existing installation placed `dataPath` at an ancestor of the client folder, and log the exact reason and paths on every path-scope rejection. +- **Quick log ZIP export on About and runtime logging toggle.** Added a quick "Save log ZIP…" button on the About page (now also bundling the latest embedded browser `-browser.log`, still excluding saves), and added a "Record runtime logs" toggle under Settings → Diagnostics to stop writing launcher logs, local server traffic logs, and `wto_ws.log`. ### Client compatibility diff --git a/apps/launcher/src/main/services/config/settings-store.ts b/apps/launcher/src/main/services/config/settings-store.ts index 0cdfef2..44de9b0 100644 --- a/apps/launcher/src/main/services/config/settings-store.ts +++ b/apps/launcher/src/main/services/config/settings-store.ts @@ -4,6 +4,7 @@ import { app } from 'electron'; import { AppError } from '@shared/errors.ts'; import { defaultSettings, SettingsSchema, type Settings, type SettingsPatch } from '@shared/schemas/settings.ts'; import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts'; +import { setLauncherLoggingEnabled } from '../diagnostics/launcher-log.ts'; /** * The launcher's settings file, `/settings.json`. Read once and cached; every change is @@ -47,6 +48,7 @@ export function updateSettings(patch: SettingsPatch): Promise { throw new AppError('settings_write_failed'); } cached = merged; + setLauncherLoggingEnabled(merged.loggingEnabled); return merged; }); pending = operation.then(() => undefined, () => undefined); diff --git a/apps/launcher/src/main/services/diagnostics/diagnostics.ts b/apps/launcher/src/main/services/diagnostics/diagnostics.ts index 219030b..97c4482 100644 --- a/apps/launcher/src/main/services/diagnostics/diagnostics.ts +++ b/apps/launcher/src/main/services/diagnostics/diagnostics.ts @@ -61,7 +61,7 @@ export async function exportDiagnostics(window: BrowserWindow | null): Promise<{ const [record, settings] = await Promise.all([readInstallRecord(), getSettings()]); const dataPath = (settings.developerMode ? settings.labDataPath : null) ?? record?.dataPath; if (dataPath) await addServerLogs(files, dataPath); - if (record) await addClientLogs(files, record); + if (record) await addClientLogs(files, record, settings.loggingEnabled); const temporary = `${result.filePath}.${randomUUID()}.tmp`; try { @@ -91,10 +91,11 @@ async function addServerLogs(files: ArchiveFiles, dataPath: string): Promise { +async function addClientLogs(files: ArchiveFiles, record: InstallRecord, loggingEnabled: boolean): Promise { const exeFolder = join(record.copyPath, dirname(GAME_FILES.executable)); const hookLogPath = join(exeFolder, HOOK_LOG_FILENAME); const hookConfigPath = join(exeFolder, HOOK_CONFIG_FILENAME); @@ -117,6 +118,9 @@ async function addClientLogs(files: ArchiveFiles, record: InstallRecord): Promis let latestClog: ListedFile | null = null; let latestClogIncluded = false; let latestClogOmittedReason: string | null = null; + let latestBrowserLog: ListedFile | null = null; + let latestBrowserLogIncluded = false; + let latestBrowserLogOmittedReason: string | null = null; const gameLogsDirStat = await safeStat(gameLogsFolder); if (gameLogsDirStat?.isDirectory()) { @@ -149,11 +153,28 @@ async function addClientLogs(files: ArchiveFiles, record: InstallRecord): Promis latestClogIncluded = added.included; latestClogOmittedReason = added.omittedReason; } + const newestBrowserLog = inspected.find((item) => item.name.toLowerCase().endsWith('-browser.log')) ?? null; + if (newestBrowserLog) { + latestBrowserLog = { + name: newestBrowserLog.name, + size: newestBrowserLog.size, + modifiedAt: newestBrowserLog.modifiedAt, + }; + const added = await addBoundedClientFile( + files, + `client-logs/game-logs/${newestBrowserLog.name}`, + join(gameLogsFolder, newestBrowserLog.name), + newestBrowserLog.size, + ); + latestBrowserLogIncluded = added.included; + latestBrowserLogOmittedReason = added.omittedReason; + } } const summary = { exportedAt: new Date().toISOString(), launcherVersion: app.getVersion(), + loggingEnabled, platform: process.platform, arch: process.arch, osRelease: release(), @@ -180,6 +201,13 @@ async function addClientLogs(files: ArchiveFiles, record: InstallRecord): Promis ...(latestClogOmittedReason ? { omittedReason: latestClogOmittedReason } : {}), } : null, + latestBrowserLog: latestBrowserLog + ? { + ...latestBrowserLog, + included: latestBrowserLogIncluded, + ...(latestBrowserLogOmittedReason ? { omittedReason: latestBrowserLogOmittedReason } : {}), + } + : null, }; files['client-logs/summary.json'] = new TextEncoder().encode(`${JSON.stringify(summary, null, 2)}\n`); } diff --git a/apps/launcher/src/main/services/diagnostics/launcher-log.ts b/apps/launcher/src/main/services/diagnostics/launcher-log.ts index 21f8943..3ac7bc0 100644 --- a/apps/launcher/src/main/services/diagnostics/launcher-log.ts +++ b/apps/launcher/src/main/services/diagnostics/launcher-log.ts @@ -1,5 +1,5 @@ import { Console } from 'node:console'; -import { appendFileSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs'; +import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { Writable } from 'node:stream'; import { app } from 'electron'; @@ -12,13 +12,26 @@ export const LAUNCHER_LOG_FILES = [ 'launcher.4.log', ] as const; +let loggingEnabled = true; +let activeLogPath: string | null = null; +let fileFailed = false; +let originalConsole = console; + 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; +function readInitialLoggingEnabled(): boolean { + try { + const raw = JSON.parse(readFileSync(join(app.getPath('userData'), 'settings.json'), 'utf8')) as { loggingEnabled?: unknown }; + return raw?.loggingEnabled !== false; + } catch { + return true; + } +} + +function ensureLogFileReady(): boolean { + if (activeLogPath) return !fileFailed; const folder = launcherLogFolder(); const active = join(folder, LAUNCHER_LOG_FILES[0]); try { @@ -28,17 +41,37 @@ export function startLauncherLogging(): void { if (existsSync(previous)) renameSync(previous, join(folder, LAUNCHER_LOG_FILES[index]!)); } writeFileSync(active, '', { flag: 'wx' }); + activeLogPath = active; + fileFailed = false; + return true; } catch (error) { + fileFailed = true; originalConsole.error('[logs] opening the launcher log failed:', error); - return; + return false; } +} + +/** Enable or disable writing launcher console output to launcher.log at runtime. */ +export function setLauncherLoggingEnabled(enabled: boolean): void { + loggingEnabled = enabled; + if (enabled && !activeLogPath && !fileFailed) { + if (ensureLogFileReady()) { + console.info(`WTOffline Launcher ${app.getVersion()} logging enabled.`); + } + } +} + +/** Rotate after taking the single-instance lock and keep the original console destinations. */ +export function startLauncherLogging(): void { + originalConsole = console; + loggingEnabled = readInitialLoggingEnabled(); + if (loggingEnabled) ensureLogFileReady(); - let fileFailed = false; const mirror = (destination: NodeJS.WriteStream, stream: string): Writable => new Writable({ write(chunk: Buffer, _encoding, done) { - if (!fileFailed) { + if (loggingEnabled && activeLogPath && !fileFailed) { try { - appendFileSync(active, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`); + appendFileSync(activeLogPath, `${new Date().toISOString()} [${stream}] ${chunk.toString('utf8')}`); } catch (error) { fileFailed = true; originalConsole.error('[logs] writing the launcher log failed:', error); diff --git a/apps/launcher/src/main/services/launch/launch-controller.ts b/apps/launcher/src/main/services/launch/launch-controller.ts index a3c5a7b..cff4d82 100644 --- a/apps/launcher/src/main/services/launch/launch-controller.ts +++ b/apps/launcher/src/main/services/launch/launch-controller.ts @@ -109,7 +109,7 @@ async function launch(job: LaunchJob): Promise { const plan = await planLaunch(job, record, settings); if (plan === null) return; const { lab, copyPath, stockPath, dataPath, port } = plan; - await buildForLaunch(job, record, plan, settings.autoSaveBackups); + await buildForLaunch(job, record, plan, settings); const publish = (phase: LaunchState['phase'], gameExit?: GameExit): void => { if (signal.aborted) return; @@ -187,10 +187,10 @@ async function planLaunch(job: LaunchJob, record: InstallRecord, settings: Setti return { lab, copyPath, stockPath, dataPath, steamLibraryConfirmed, port }; } -async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, autoSaveBackups: boolean): Promise { +async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: LaunchPlan, settings: Settings): Promise { const signal = job.stop.signal; const { lab, copyPath, stockPath, dataPath, port, steamLibraryConfirmed } = plan; - if (autoSaveBackups) { + if (settings.autoSaveBackups) { for (const { userId } of new AccountStore(dataPath).all()) { signal.throwIfAborted(); await saveBackup({ ...record, dataPath }, userId, 'launch'); @@ -209,6 +209,7 @@ async function buildForLaunch(job: LaunchJob, record: InstallRecord, plan: Launc steamLibraryConfirmed, ...resourcePaths(), ...(record.decalCacheId ? { decalCache: decalCachePath(lab ? record.dataPath : dataPath, record.decalCacheId) } : {}), + hookLogging: settings.loggingEnabled, acceptedUnavailable: record.unavailablePatches.map(({ patchId }) => patchId), }, signal, (filesWritten, filesTotal, file) => { writtenFiles = filesWritten; diff --git a/apps/launcher/src/main/services/launch/local-server.ts b/apps/launcher/src/main/services/launch/local-server.ts index 022c897..8ea0eee 100644 --- a/apps/launcher/src/main/services/launch/local-server.ts +++ b/apps/launcher/src/main/services/launch/local-server.ts @@ -34,13 +34,17 @@ export async function localServerReady(port: number, pid?: number, signal?: Abor } export async function startLocalServer( - { gameFolder, dataFolder, port }: Omit, signal: AbortSignal, + { gameFolder, dataFolder, port, loggingEnabled = true }: Omit, signal: AbortSignal, ): Promise { signal.throwIfAborted(); - const worker = utilityProcess.fork(join(import.meta.dirname, 'server-worker.js'), [gameFolder, dataFolder, String(port)], { - serviceName: 'WTOffline local server', - stdio: 'pipe', - }); + const worker = utilityProcess.fork( + join(import.meta.dirname, 'server-worker.js'), + [gameFolder, dataFolder, String(port), loggingEnabled ? '1' : '0'], + { + serviceName: 'WTOffline local server', + stdio: 'pipe', + }, + ); forwardProcessOutput(worker.stdout, 'server', 'info'); forwardProcessOutput(worker.stderr, 'server', 'error'); diff --git a/apps/launcher/src/main/services/launch/ordinary-launch.ts b/apps/launcher/src/main/services/launch/ordinary-launch.ts index 32b9f13..533b646 100644 --- a/apps/launcher/src/main/services/launch/ordinary-launch.ts +++ b/apps/launcher/src/main/services/launch/ordinary-launch.ts @@ -49,7 +49,10 @@ export async function runOrdinaryLaunch( const args = parseLaunchArguments(settings.launchArguments); if (!args) throw new AppError('launch_game_failed'); publish('starting-server'); - const server = await startLocalServer({ gameFolder: copyPath, dataFolder: dataPath, port }, signal); + const server = await startLocalServer( + { gameFolder: copyPath, dataFolder: dataPath, port, loggingEnabled: settings.loggingEnabled }, + signal, + ); const stop = new AbortController(); const runSignal = AbortSignal.any([signal, stop.signal]); const serverExited = server.exited.then(() => { throw new AppError('launch_server_exited'); }); diff --git a/apps/launcher/src/main/workers/build-protocol.ts b/apps/launcher/src/main/workers/build-protocol.ts index ecd1ed9..4b1f2e1 100644 --- a/apps/launcher/src/main/workers/build-protocol.ts +++ b/apps/launcher/src/main/workers/build-protocol.ts @@ -10,6 +10,7 @@ export interface BuildRequest { readonly patches: string; readonly networkHookLibrary: string; readonly decalCache?: string; + readonly hookLogging: boolean; readonly acceptedUnavailable: readonly string[]; } diff --git a/apps/launcher/src/main/workers/build-worker.ts b/apps/launcher/src/main/workers/build-worker.ts index 26b63c7..dfac45c 100644 --- a/apps/launcher/src/main/workers/build-worker.ts +++ b/apps/launcher/src/main/workers/build-worker.ts @@ -41,6 +41,7 @@ function build(request: BuildRequest): void { port: request.port, multiVehiclePackIds: multiVehiclePackIds(request.dataPath, console.info), placeholderDecals: decalCache === undefined, + hookLogging: request.hookLogging, }); const unavailable = [...result.exePatches.failures, ...result.guiPatches.failures, ...result.nativeModules.failures]; const accepted = new Set(request.acceptedUnavailable); diff --git a/apps/launcher/src/main/workers/server-worker.ts b/apps/launcher/src/main/workers/server-worker.ts index e8b3b60..90e125c 100644 --- a/apps/launcher/src/main/workers/server-worker.ts +++ b/apps/launcher/src/main/workers/server-worker.ts @@ -3,13 +3,14 @@ import { startServer } from '@wto/server'; export type ServerWorkerStatus = 'listening' | 'port-busy' | 'failed'; async function serve(): Promise { - const [gameFolder, dataFolder, portText] = process.argv.slice(2); + const [gameFolder, dataFolder, portText, loggingFlag] = process.argv.slice(2); const port = Number(portText); if (!gameFolder || !dataFolder || !Number.isInteger(port) || port < 1 || port > 65535) { throw new Error('Invalid local server arguments.'); } - const server = await startServer({ gameFolder, dataFolder, port, report: console.info }); - console.info('Traffic log:', server.logFolder); + const loggingEnabled = loggingFlag !== '0'; + const server = await startServer({ gameFolder, dataFolder, port, loggingEnabled, report: console.info }); + if (server.logFolder) console.info('Traffic log:', server.logFolder); process.parentPort.once('message', () => { void server.close().then(() => process.exit(0)).catch((error: unknown) => { console.error('Could not close the local server:', error); diff --git a/apps/launcher/src/renderer/src/App.tsx b/apps/launcher/src/renderer/src/App.tsx index ac52eb0..6a9bac7 100644 --- a/apps/launcher/src/renderer/src/App.tsx +++ b/apps/launcher/src/renderer/src/App.tsx @@ -149,13 +149,26 @@ export function App({ info, initialSettings, initialCopies }: AppProps) { bar: home, }; case 'about': - return { side: homeSide, main: , bar: home }; + return { + side: homeSide, + main: ( + + ), + bar: home, + }; case 'settings': { const sections = SETTINGS_SECTIONS.filter((section) => info.development || section !== 'dev'); const content = { general: , launch: , - diag: , + diag: , dev: , }; return { diff --git a/apps/launcher/src/renderer/src/i18n/locales/en.json b/apps/launcher/src/renderer/src/i18n/locales/en.json index 83e1afd..44010bf 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/en.json +++ b/apps/launcher/src/renderer/src/i18n/locales/en.json @@ -529,11 +529,15 @@ "reset": "Restore default" }, "diagnostics": { + "recordLogs": "Record runtime logs", + "recordLogsToggle": "Write launcher, local server, and hook logs", + "recordLogsHint": "When disabled, stops writing launcher logs, local server traffic logs, and wto_ws.log (the game engine's own .game_logs are unaffected). Re-enable before exporting logs for troubleshooting.", + "loggingDisabledNotice": "Runtime logging is currently disabled; exported archives include only existing logs and configuration.", "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", + "exportHint": "Save launcher, local server, and game logs, settings, and the installation record to a ZIP file (excludes saves)", "save": "Export…", "saved": "Diagnostics saved to {{path}}.", "serverStatus": "Local server status", @@ -571,6 +575,12 @@ "about": { "launcher": "Launcher {{version}}", "supported": "Supported game versions: {{versions}}", + "feedback": { + "title": "Feedback and logs", + "export": "Save all logs", + "exportHint": "Pack launcher, local server, and game logs into a ZIP file for issue reports (excludes saves).", + "exportButton": "Save log ZIP…" + }, "pack": { "title": "Adaptation data", "current": "In use", 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 06d171e..4a600f3 100644 --- a/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json +++ b/apps/launcher/src/renderer/src/i18n/locales/zh-CN.json @@ -529,11 +529,15 @@ "reset": "恢复默认" }, "diagnostics": { + "recordLogs": "生成运行日志", + "recordLogsToggle": "记录启动器、本地服务器和钩子日志", + "recordLogsHint": "关闭后停止写入启动器日志、本地服务器流量日志和 wto_ws.log(不影响游戏引擎原生的 .game_logs)。导出日志排查问题前建议重新开启。", + "loggingDisabledNotice": "当前已关闭运行日志记录,导出的压缩包仅包含已有历史日志和配置。", "logs": "日志", "logsHint": "启动器运行日志", "openLogs": "打开日志文件夹", "export": "导出诊断信息", - "exportHint": "导出包含日志、设置和安装记录的 ZIP 文件", + "exportHint": "导出包含启动器、本地服务器与游戏日志、设置和安装记录的 ZIP 文件(不含存档)", "save": "导出…", "saved": "诊断信息已保存到 {{path}}。", "serverStatus": "本地服务器状态页", @@ -571,6 +575,12 @@ "about": { "launcher": "启动器 {{version}}", "supported": "支持的游戏版本:{{versions}}", + "feedback": { + "title": "问题反馈", + "export": "保存全部日志", + "exportHint": "打包启动器、本地服务器及游戏日志为 ZIP 文件以便反馈问题(不含存档)。", + "exportButton": "保存日志 ZIP…" + }, "pack": { "title": "适配数据", "current": "当前使用", diff --git a/apps/launcher/src/renderer/src/pages/about/AboutPage.tsx b/apps/launcher/src/renderer/src/pages/about/AboutPage.tsx index e465bdb..8091aaa 100644 --- a/apps/launcher/src/renderer/src/pages/about/AboutPage.tsx +++ b/apps/launcher/src/renderer/src/pages/about/AboutPage.tsx @@ -1,7 +1,9 @@ +import { useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Notice } from '../../components/Notice.tsx'; import { Row } from '../../components/Row.tsx'; import { Sheet } from '../../components/Sheet.tsx'; +import { ipcInvoke } from '../../ipc.ts'; import type { AppUpdateState } from '../../shell/useAppUpdate.ts'; import { AppUpdateSection } from './AppUpdateSection.tsx'; import type { PatchPackState } from '../../shell/usePatchPack.ts'; @@ -11,10 +13,12 @@ interface AboutPageProps { readonly supportedVersions: readonly string[]; readonly patchPack: PatchPackState; readonly appUpdate: AppUpdateState; + readonly loggingEnabled: boolean; + readonly onError: (error: unknown) => void; } -/** The launcher's version, the game versions it supports, adaptation pack updates, and the project statement. */ -export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate }: AboutPageProps) { +/** The launcher's version, the game versions it supports, adaptation pack updates, log export, and the project statement. */ +export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUpdate, loggingEnabled, onError }: AboutPageProps) { const { t } = useTranslation(); return ( @@ -28,12 +32,48 @@ export function AboutPage({ launcherVersion, supportedVersions, patchPack, appUp +

{t('about.statement')}

{t('about.statementBody')}

); } +function FeedbackLogsSection({ loggingEnabled, onError }: { + readonly loggingEnabled: boolean; + readonly onError: (error: unknown) => void; +}) { + 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 ( + <> +

{t('about.feedback.title')}

+ + + + {!loggingEnabled &&

{t('settings.diagnostics.loggingDisabledNotice')}

} + {savedPath &&

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

} + + ); +} + function PatchPackSection({ state }: { readonly state: PatchPackState }) { const { t } = useTranslation(); const { active, check, busy } = state; diff --git a/apps/launcher/src/renderer/src/pages/settings/DiagnosticsSettings.tsx b/apps/launcher/src/renderer/src/pages/settings/DiagnosticsSettings.tsx index cec0c41..f6a1434 100644 --- a/apps/launcher/src/renderer/src/pages/settings/DiagnosticsSettings.tsx +++ b/apps/launcher/src/renderer/src/pages/settings/DiagnosticsSettings.tsx @@ -1,19 +1,25 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; +import type { Settings } from '@shared/schemas/settings.ts'; import { Row } from '../../components/Row.tsx'; import { Sheet } from '../../components/Sheet.tsx'; import { ipcInvoke } from '../../ipc.ts'; interface DiagnosticsSettingsProps { + readonly settings: Settings; readonly serverRunning: boolean; readonly onError: (error: unknown) => void; } -export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSettingsProps) { +export function DiagnosticsSettings({ settings, onError, serverRunning }: DiagnosticsSettingsProps) { const { t } = useTranslation(); const [exporting, setExporting] = useState(false); const [savedPath, setSavedPath] = useState(null); + const updateLogging = (loggingEnabled: boolean): void => { + ipcInvoke('settings:update', { loggingEnabled }).catch(onError); + }; + async function save(): Promise { setExporting(true); setSavedPath(null); @@ -29,6 +35,16 @@ export function DiagnosticsSettings({ onError, serverRunning }: DiagnosticsSetti return ( + + + + {!settings.loggingEnabled &&

{t('settings.diagnostics.loggingDisabledNotice')}

} {savedPath &&

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

}
); diff --git a/apps/launcher/src/shared/schemas/settings.ts b/apps/launcher/src/shared/schemas/settings.ts index fb44043..ebfd269 100644 --- a/apps/launcher/src/shared/schemas/settings.ts +++ b/apps/launcher/src/shared/schemas/settings.ts @@ -28,6 +28,8 @@ export const SettingsSchema = z.object({ windowClose: WindowCloseSchema.default('quit'), afterGameStarts: AfterGameStartsSchema.default('minimize'), autoSaveBackups: z.boolean().default(true), + /** Write launcher, local server traffic, and wto_ws.log files; does not affect game .game_logs. */ + loggingEnabled: z.boolean().default(true), launchPortMode: PortModeSchema.default('auto'), launchPort: PortSchema.default(27015), closeServerOnGameExit: z.boolean().default(true), @@ -50,6 +52,7 @@ export const SettingsPatchSchema = z.object({ windowClose: WindowCloseSchema.optional(), afterGameStarts: AfterGameStartsSchema.optional(), autoSaveBackups: z.boolean().optional(), + loggingEnabled: z.boolean().optional(), launchPortMode: PortModeSchema.optional(), launchPort: PortSchema.optional(), closeServerOnGameExit: z.boolean().optional(), diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index bc132bb..ae8c1f6 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -69,6 +69,8 @@ export interface ServerOptions { readonly port: number; /** Start-up progress lines (static data extraction, game modes). */ readonly report?: (line: string) => void; + /** Whether to write traffic logs under `/logs`; defaults to true. */ + readonly loggingEnabled?: boolean; } export const LOOPBACK = '127.0.0.1'; @@ -143,7 +145,7 @@ export async function startServer(options: ServerOptions): Promise without a valid port the hooks still answer every host name * locally but refuse every connection that would leave the machine + * log=0|1 optional, defaults to 1; when 0, wto_ws.log is not opened * exe.time_date_stamp=0x... the executable the native values were resolved for * exe.size_of_image=0x... * native.= what the LocalMP modules need from the executable: RVAs of @@ -33,6 +34,7 @@ typedef struct NativeValue { static wchar_t g_folder[MAX_PATH]; static CRITICAL_SECTION g_log_lock; static FILE *g_log; +static int g_log_enabled = 1; static NativeValue g_native[NATIVE_VALUES_MAX]; static size_t g_native_count; static int64_t g_exe_time_date_stamp = -1; @@ -98,6 +100,8 @@ static void read_settings(void) line[strcspn(line, "\r\n")] = '\0'; if (strncmp(line, "port=", 5) == 0) read_port(line + 5); + else if (strncmp(line, "log=", 4) == 0) + g_log_enabled = atoi(line + 4) != 0; else if (strncmp(line, "exe.time_date_stamp=", 20) == 0) parse_value(line + 20, &g_exe_time_date_stamp); else if (strncmp(line, "exe.size_of_image=", 18) == 0) @@ -140,7 +144,7 @@ void config_load(HMODULE self) InitializeCriticalSection(&g_log_lock); find_folder(self); read_settings(); - if (_snwprintf_s(path, MAX_PATH, _TRUNCATE, L"%swto_ws.log", g_folder) >= 0) + if (g_log_enabled && _snwprintf_s(path, MAX_PATH, _TRUNCATE, L"%swto_ws.log", g_folder) >= 0) g_log = _wfsopen(path, L"w", _SH_DENYWR); log_line("wto_ws: local server port %u%s", g_service_port, g_service_port ? "" : " (none: outside connections are refused)"); log_line("wto_ws: %u native value(s) for the LocalMP modules", (unsigned)g_native_count); diff --git a/packages/patcher/src/build-game-copy.ts b/packages/patcher/src/build-game-copy.ts index 20ddcce..a62de2a 100644 --- a/packages/patcher/src/build-game-copy.ts +++ b/packages/patcher/src/build-game-copy.ts @@ -44,6 +44,8 @@ export interface GameCopyInputs { readonly multiVehiclePackIds: readonly string[]; /** Store the placeholder decal index; false when the player's own web cache is copied. */ readonly placeholderDecals: boolean; + /** Whether wto_ws.dll writes win64/wto_ws.log; defaults to true. */ + readonly hookLogging?: boolean; } /** One file of the game copy, by its path relative to the copy folder. */ @@ -96,7 +98,9 @@ export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild { const mainPack = rebuildMainPack(inputs.stock.mainPack, endpoint, bundles); const executableFolder = dirname(GAME_FILES.executable); - const hookSettings = networkHookSettings(endpoint, stockImage, native.values); + const hookSettings = networkHookSettings(endpoint, stockImage, native.values, { + loggingEnabled: inputs.hookLogging ?? true, + }); const files: GameCopyFile[] = [ { path: GAME_FILES.charPack, content: charPack }, { path: GAME_FILES.mainPack, content: mainPack.pack }, diff --git a/packages/patcher/src/network/network-hook.ts b/packages/patcher/src/network/network-hook.ts index abe2b14..583dbbf 100644 --- a/packages/patcher/src/network/network-hook.ts +++ b/packages/patcher/src/network/network-hook.ts @@ -17,7 +17,12 @@ export function networkHookSettings( endpoint: LocalEndpoint, stock: PeImage, nativeValues: ReadonlyMap, + options?: { readonly loggingEnabled?: boolean }, ): { name: string; content: Uint8Array } { - const lines = [`port=${endpoint.port}`, ...nativeSettingsLines(stock, nativeValues)]; + const lines = [ + `port=${endpoint.port}`, + ...(options?.loggingEnabled === false ? ['log=0'] : []), + ...nativeSettingsLines(stock, nativeValues), + ]; return { name: SETTINGS, content: new TextEncoder().encode(`${lines.join('\n')}\n`) }; }