import "./styles.css"; import type { ProcessInfo, UtilityResult } from "../shared/ipc"; type TabId = "processes" | "crash" | "utility"; declare global { interface Window { api: { info(): Promise; crashRenderer(): Promise<{ ok: boolean }>; runUtility(n: number): Promise; }; __setTab?: (tab: TabId) => void; __snapshot?: () => unknown; } } const state: { tab: TabId; info: ProcessInfo | null; utility: UtilityResult | null; busy: boolean; } = { tab: "processes", info: null, utility: null, busy: false }; const tabs: Array<{ id: TabId; label: string }> = [ { id: "processes", label: "进程表" }, { id: "crash", label: "崩溃隔离" }, { id: "utility", label: "utilityProcess" }, ]; function escapeHtml(value: string): string { return value .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll('"', """); } function processes(info: ProcessInfo): string { return `

操作系统进程

${info.processes .map( (entry) => ``, ) .join("")}
类型PID内存
${escapeHtml(entry.type)}${entry.pid}${entry.memoryMB} MB

主进程 ${info.mainPid},渲染进程 ${info.rendererPid},GPU 进程 ${info.gpuPid}。用活动监视器按 PID 搜索可对照。

`; } function crash(info: ProcessInfo): string { return `

崩溃隔离

点击按钮会让当前渲染进程崩溃。主进程不会退出,会在 300ms 后重载窗口;崩溃次数记录在主进程里。

当前崩溃次数
${info.crashCount}

崩溃后页面会重载,这个页面上的临时状态会丢失;主进程的计数会保留。

`; } function utility(stateUtility: UtilityResult | null): string { return `

utilityProcess

主进程把 CPU 计算交给一个 utility 进程:它有自己的 PID、不会阻塞窗口,崩溃也不会带走主进程。

${ stateUtility ? `

结果:${stateUtility.sum},耗时 ${stateUtility.elapsedMs}ms。

` : `

还没有运行。

` }

父进程通过 postMessage 发任务,子进程通过 process.parentPort 回包;参数与结果都必须可序列化。

`; } function render(): void { const root = document.querySelector("#app"); if (!root) return; const info = state.info; const body = !info ? `

正在读取进程信息…

` : state.tab === "processes" ? processes(info) : state.tab === "crash" ? crash(info) : utility(state.utility); root.innerHTML = `

进程模型

一个主进程、每个窗口一个渲染进程、按需启动 utility 进程

${body}
`; for (const button of root.querySelectorAll("[data-tab]")) { button.addEventListener("click", () => { const tab = button.dataset.tab; if (tab === "processes" || tab === "crash" || tab === "utility") { state.tab = tab; render(); } }); } root.querySelector("#crash-button")?.addEventListener("click", () => { void window.api.crashRenderer(); }); root.querySelector("#utility-button")?.addEventListener("click", async () => { if (state.busy) return; state.busy = true; try { state.utility = await window.api.runUtility(1000); state.info = await window.api.info(); } finally { state.busy = false; render(); } }); } async function boot(): Promise { state.info = await window.api.info(); render(); window.__setTab = (tab) => { state.tab = tab; render(); }; window.__snapshot = () => ({ tab: state.tab, mainPid: state.info?.mainPid, rendererPid: state.info?.rendererPid, }); } void boot();