"use strict"; // Khaos stability log (client-freeze, 2026-10-08; docs/client/client-freeze.md). A player whose PC "froze" restarts the // client afterwards, and the F11 report only carries the current session's in-memory logs: nothing showed what the // client was doing when it happened. This writes a small file the next F11 report carries (translator bugReport.ts): // /stability.log (installed client: %LOCALAPPDATA%\\logs; dev: /logs) // - the machine: CPU, RAM, the GPU Chromium uses (vendor/device/driver) and its feature status, // - "previous session ended unexpectedly" when the last run never reached a clean exit (hard reset, power loss, // killed while frozen), with its last health line, // - every GPU / renderer / utility process crash, window unresponsive / responsive (with the duration), // main-process stalls, // - a health line every 5 minutes (each minute while free RAM is low): free RAM, private memory per process type. // Writes are tiny and synchronous; the file rotates at 1 MB (stability.log.1). const fs = require("fs"); const os = require("os"); const path = require("path"); const MAX_BYTES = 1024 * 1024; const BEAT_MS = 30_000; const HEALTH_MS = 60_000; const HEALTH_LOG_EVERY = 5; // health samples between two logged lines (when nothing is wrong) const LOW_FREE_RATIO = 0.12; const STALL_MS = 2_000; let file = null; let stateFile = null; let state = null; function line(text) { if (!file) return; try { try { if (fs.statSync(file).size > MAX_BYTES) fs.renameSync(file, `${file}.1`); } catch { /* first line */ } fs.appendFileSync(file, `${new Date().toISOString()} ${text}\n`); } catch { /* diagnostics only */ } } function saveState() { try { fs.writeFileSync(stateFile, JSON.stringify(state)); } catch { /* diagnostics only */ } } const mb = (bytes) => Math.round(bytes / 1048576); /** Private memory per process type (MB) and free RAM, from Electron's own process metrics. */ function health(app) { const byType = {}; for (const m of app.getAppMetrics()) { const key = m.type === "Utility" && m.serviceName ? `Utility:${m.serviceName}` : m.type; // privateBytes is Windows-only (KB); workingSetSize elsewhere const kb = m.memory.privateBytes ?? m.memory.workingSetSize ?? 0; byType[key] = (byType[key] ?? 0) + Math.round(kb / 1024); } const total = Object.values(byType).reduce((a, b) => a + b, 0); return { freeMB: mb(os.freemem()), totalMB: mb(os.totalmem()), clientMB: total, byType }; } function describe(h) { const parts = Object.entries(h.byType) .sort((a, b) => b[1] - a[1]) .map(([k, v]) => `${k}=${v}`); return `free RAM ${h.freeMB}/${h.totalMB} MB, client ${h.clientMB} MB (${parts.join(" ")})`; } /** * Starts the stability log. Call before app "ready" (the crash listeners must be in place before any window). * @param {{ app: import("electron").App, logDir: string, version?: string, gpuMode?: string }} opt */ function start({ app, logDir, version = "", gpuMode = "" }) { try { fs.mkdirSync(logDir, { recursive: true }); } catch { return; } file = path.join(logDir, "stability.log"); stateFile = path.join(logDir, "session-state.json"); // ---------------------------------------------------------------- the previous run let previous = null; try { previous = JSON.parse(fs.readFileSync(stateFile, "utf8")); } catch { /* first run, or unreadable */ } if (previous && !previous.clean && previous.pid !== process.pid) { const ran = Math.round(((previous.lastBeatAt ?? previous.startedAt) - previous.startedAt) / 60000); line( `PREVIOUS SESSION ENDED UNEXPECTEDLY: started ${new Date(previous.startedAt).toISOString()}, last sign of life ` + `${new Date(previous.lastBeatAt ?? previous.startedAt).toISOString()} (${ran} min in), ` + `GPU crashes ${previous.gpuCrashes ?? 0}, unresponsive ${previous.unresponsive ?? 0}` + (previous.lastHealth ? `; last health: ${previous.lastHealth}` : ""), ); } state = { pid: process.pid, startedAt: Date.now(), lastBeatAt: Date.now(), clean: false, gpuCrashes: 0, unresponsive: 0 }; saveState(); const cpus = os.cpus(); line( `--- start ${version} pid=${process.pid} electron=${process.versions.electron} chrome=${process.versions.chrome} ` + `${os.platform()} ${os.release()} ${os.arch()}; CPU ${cpus[0]?.model?.trim() ?? "?"} x${cpus.length}; ` + `RAM ${mb(os.totalmem())} MB (free ${mb(os.freemem())} MB); graphics card: ${gpuMode || "?"}; switches: ${process.argv.filter((a) => a.startsWith("--")).join(" ") || "none"}`, ); // ---------------------------------------------------------------- crashes, hangs app.on("child-process-gone", (_e, d) => { if (d.type === "GPU") state.gpuCrashes += 1; line(`PROCESS GONE type=${d.type} reason=${d.reason} exitCode=${d.exitCode}${d.name ? ` name=${d.name}` : ""}${d.serviceName ? ` service=${d.serviceName}` : ""}`); saveState(); }); app.on("render-process-gone", (_e, contents, d) => { let url = ""; try { url = contents.getURL().replace(/[?#].*$/, ""); } catch { /* destroyed */ } line(`RENDERER GONE reason=${d.reason} exitCode=${d.exitCode} page=${url}`); }); app.on("browser-window-created", (_e, win) => { let since = 0; win.on("unresponsive", () => { since = Date.now(); state.unresponsive += 1; saveState(); let h = ""; try { h = describe(health(app)); } catch { /* metrics unavailable */ } line(`WINDOW UNRESPONSIVE (the page's main thread is busy or hung); ${h}`); }); win.on("responsive", () => { if (since) line(`window responsive again after ${Math.round((Date.now() - since) / 1000)} s`); since = 0; }); }); const clean = () => { state.clean = true; state.lastBeatAt = Date.now(); saveState(); }; app.on("will-quit", () => { line("exit (clean)"); clean(); }); // ---------------------------------------------------------------- GPU, heartbeat, health app.whenReady().then(() => { let gpuLogged = false; const logGpu = () => { if (gpuLogged) return; gpuLogged = true; // "complete" names the adapter Chromium draws with (glRenderer); asked once, a few seconds after the start app .getGPUInfo("complete") .then((info) => { const hex = (n) => `0x${Number(n).toString(16).padStart(4, "0")}`; const devices = (info.gpuDevice ?? []) .map((g) => `${g.active ? "*" : ""}${hex(g.vendorId)}:${g.deviceString || hex(g.deviceId)}${g.driverVersion ? ` driver ${g.driverVersion}` : ""}`) .join(", "); const aux = info.auxAttributes ?? {}; const status = Object.entries(app.getGPUFeatureStatus()) .filter(([k]) => /webgl|compositing|rasterization|2d_canvas/.test(k)) .map(([k, v]) => `${k}=${v}`) .join(" "); line(`GPU in use: ${aux.glRenderer || "?"}; adapters: ${devices || "unknown"}; ${status}`); }) .catch(() => {}); }; setTimeout(logGpu, 5_000).unref(); // Sleep / resume resets GPUs (lost WebGL contexts) and shows as a long "stall": name it. try { const { powerMonitor } = require("electron"); powerMonitor.on("suspend", () => line("system suspend (sleep)")); powerMonitor.on("resume", () => line("system resume")); } catch { /* not available */ } let n = 0; setInterval(() => { let h = null; try { h = health(app); } catch { return; } const text = describe(h); state.lastHealth = text; state.lastBeatAt = Date.now(); const low = h.freeMB < h.totalMB * LOW_FREE_RATIO; if (low || n % HEALTH_LOG_EVERY === 0) line(`${low ? "LOW MEMORY " : "health "}${text}`); n += 1; saveState(); }, HEALTH_MS).unref(); setInterval(() => { state.lastBeatAt = Date.now(); saveState(); }, BEAT_MS).unref(); }); // The main process itself: a stalled event loop freezes the window as much as a hung page (network packets, asset // requests and window messages all go through it). let last = Date.now(); setInterval(() => { const now = Date.now(); const late = now - last - 1000; last = now; if (late >= STALL_MS) line(`main process stalled ${late} ms (busy main thread, or the whole PC was asleep or frozen)`); }, 1000).unref(); } module.exports = { start, line };