import {
decideRecovery,
type Check,
type CrashRow,
type Snapshot,
} from "../shared/ipc";
function escape(text: string): string {
return text.replace(/[&<>"]/g, (char) => {
if (char === "&") return "&";
if (char === "<") return "<";
if (char === ">") return ">";
return """;
});
}
function time(at: number): string {
return new Date(at).toLocaleTimeString("zh-CN", { hour12: false });
}
function shorten(value: string, size = 34): string {
if (value.length <= size) return value;
return `${value.slice(0, size / 2)}…${value.slice(-size / 2)}`;
}
function checkRow(check: Check): string {
return `
${check.pass ? "PASS" : "FAIL"}
${escape(check.label)}
${escape(check.detail)}
`;
}
function historyRow(row: CrashRow): string {
return `
${time(row.at)}
${escape(row.reason)}
exit ${row.exitCode}
${row.recovered ? "已恢复" : "待恢复"}
${row.recovered ? `${row.recoveryMs}ms` : "—"}
${row.dumpCount} dmp
`;
}
export function mountApp(root: HTMLElement): void {
root.innerHTML = `
正在读取崩溃状态…
崩溃与恢复
—
1render-process-gone
2落盘崩溃记录
3退避后 reload
4恢复并提示
恢复策略
reason × attempts
| reason | 次数 | 动作 | 退避 |
${[
["killed", 0],
["crashed", 0],
["crashed", 1],
["crashed", 2],
["crashed", 3],
]
.map(([reason, attempts]) => {
const row = decideRecovery(
String(reason),
Number(attempts),
);
return `| ${escape(String(reason))} | ${attempts} | ${row.action} | ${row.delayMs}ms |
`;
})
.join("")}
crashReporter
本地 dump,不上传
渲染进程错误边界
界面已降级
主进程仍存活,崩溃历史与 dump 不受影响。可以关闭提示继续操作,
或重新加载界面恢复完整状态。
`;
const score = root.querySelector('[data-testid="score"]');
const checkCount = root.querySelector(
'[data-testid="check-count"]',
);
const checksEl = root.querySelector('[data-testid="checks"]');
const banner = root.querySelector('[data-testid="banner"]');
const recoveryCount = root.querySelector(
'[data-testid="recovery-count"]',
);
const statsEl = root.querySelector('[data-testid="stats"]');
const historyEl = root.querySelector('[data-testid="history"]');
const dumpCount = root.querySelector(
'[data-testid="dump-count"]',
);
const reporterEl = root.querySelector(
'[data-testid="reporter"]',
);
const eventsEl = root.querySelector('[data-testid="events"]');
const overlay = root.querySelector(
'[data-testid="error-overlay"]',
);
const errorMessage = root.querySelector(
'[data-testid="error-message"]',
);
const autoPill = root.querySelector('[data-testid="auto-pill"]');
let state: Snapshot | null = null;
function renderChecks(): void {
if (!state) return;
if (checksEl) checksEl.innerHTML = state.checks.map(checkRow).join("");
if (checkCount) {
const passed = state.checks.filter((check) => check.pass).length;
checkCount.textContent = `${passed}/${state.checks.length} 通过`;
}
if (score) {
score.textContent = `${state.score} / 100`;
score.className = `pill ${state.score === 100 ? "ok-pill" : "bad-pill"}`;
}
}
function renderCrash(): void {
if (!state) return;
const crash = state.history[0];
if (banner) {
banner.textContent = crash?.recovered
? `已从崩溃恢复:${crash.reason} · exit ${crash.exitCode} · ${crash.recoveryMs}ms · dump ${crash.dumpCount}`
: crash
? `检测到崩溃:${crash.reason} · exit ${crash.exitCode},等待恢复`
: "运行正常,自动恢复已启用";
banner.className = `banner ${crash ? (crash.recovered ? "ok" : "warn") : ""}`;
}
if (recoveryCount) {
recoveryCount.textContent = `${state.recovery.recoveredCount} 次恢复`;
}
if (autoPill) {
autoPill.textContent = `auto-recover: ${state.recovery.autoRecover ? "on" : "off"}`;
autoPill.className = `pill ${state.recovery.autoRecover ? "ok-pill" : "bad-pill"}`;
}
if (statsEl) {
statsEl.innerHTML = `
崩溃次数${state.history.length}
已恢复${state.recovery.recoveredCount}
上次恢复${state.recovery.lastRecoveryMs ? `${state.recovery.lastRecoveryMs}ms` : "—"}
dump${state.crashReporter.dumpCount}`;
}
if (dumpCount) {
dumpCount.textContent = `${state.crashReporter.dumpCount} dmp · ${state.crashReporter.pendingCount} pending`;
}
if (historyEl) {
historyEl.innerHTML =
state.history.length === 0
? `尚无崩溃记录`
: state.history.slice(0, 8).map(historyRow).join("");
}
}
function renderReporter(): void {
if (!state || !reporterEl) return;
const reporter = state.crashReporter;
reporterEl.innerHTML = `
started${reporter.started}
uploadToServer${reporter.uploadToServer}
directory${escape(shorten(reporter.directory, 36))}
dumps${reporter.dumpCount} / pending ${reporter.pendingCount}
lastError${escape(shorten(state.lastError?.message ?? "none", 30))}`;
}
function renderEvents(): void {
if (!eventsEl || !state) return;
eventsEl.innerHTML =
state.events.length === 0
? `暂无活动`
: state.events
.slice(0, 8)
.map(
(row) => `
${time(row.at)}
${escape(row.kind)}
${escape(row.detail)}
`,
)
.join("");
}
function render(next: Snapshot): void {
state = next;
renderChecks();
renderCrash();
renderReporter();
renderEvents();
}
function showFallback(message: string): void {
if (errorMessage) errorMessage.textContent = message;
if (overlay) overlay.hidden = false;
}
window.addEventListener("error", (event) => {
const message = event.message || "unknown renderer error";
showFallback(message);
void window.api.crash
.reportError({
message,
source: event.filename || "renderer",
line: event.lineno || 0,
})
.then(render);
});
window.addEventListener("unhandledrejection", (event) => {
const reason = event.reason;
const message =
reason instanceof Error ? reason.message : String(reason ?? "unknown");
showFallback(message);
void window.api.crash
.reportError({ message, source: "unhandledrejection", line: 0 })
.then(render);
});
window.__simulateError = () => {
setTimeout(() => {
throw new Error("BOOM: renderer boundary probe");
}, 0);
};
void window.api.crash.ready().then(render);
window.api.crash.onEvent(() => {
void window.api.crash.snapshot().then(render);
});
root
.querySelector('[data-testid="refresh"]')
?.addEventListener("click", async () => {
render(await window.api.crash.refresh());
});
root
.querySelector('[data-testid="crash"]')
?.addEventListener("click", async () => {
render(await window.api.crash.crashRenderer());
});
root
.querySelector('[data-testid="reload"]')
?.addEventListener("click", async () => {
await window.api.crash.reload();
});
root
.querySelector('[data-testid="simulate-error"]')
?.addEventListener("click", () => {
window.__simulateError?.();
});
root
.querySelector('[data-testid="clear-history"]')
?.addEventListener("click", async () => {
render(await window.api.crash.clearHistory());
});
root
.querySelector('[data-testid="error-dismiss"]')
?.addEventListener("click", () => {
if (overlay) overlay.hidden = true;
});
root
.querySelector('[data-testid="error-reload"]')
?.addEventListener("click", () => {
location.reload();
});
const sleep = (value: number): Promise =>
new Promise((resolve) => setTimeout(resolve, value));
window.__prepareShots = async (stage) => {
document.body.dataset.shot = stage;
if (stage === "overview") {
render(await window.api.crash.refresh());
return;
}
if (stage === "recovered") {
render(await window.api.crash.refresh());
document.querySelector(".crash-card")?.scrollIntoView({ block: "start" });
return;
}
window.__simulateError?.();
await sleep(250);
};
window.__demo = async () => {
const next = await window.api.crash.snapshot();
state = next;
const last = next.history[0];
return {
score: next.score,
checks: next.checks.length,
passed: next.checks.filter((check) => check.pass).length,
crashes: next.history.length,
lastReason: last?.reason ?? "",
lastExit: last?.exitCode ?? 0,
lastRecovered: last?.recovered ?? false,
recoveryMs: last?.recoveryMs ?? 0,
dumps: next.crashReporter.dumpCount,
pending: next.crashReporter.pendingCount,
historyExists:
next.checks.find((check) => check.id === "history-file")?.pass ?? false,
errorHookReady: next.errorHookReady,
lastError: next.lastError?.message ?? "",
banner: banner?.textContent ?? "",
};
};
}