desktopStabilityTelemetry.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. /* eslint-disable max-lines -- 稳定性上报集中单模块,拆分反而增加跨文件状态同步 */
  2. import { randomUUID } from "node:crypto";
  3. import armsRum from "@arms/rum-electron";
  4. import { BrowserWindow, type WebContents } from "electron";
  5. import {
  6. mapZCodeEnvToArmsRumEnv,
  7. type HostAgentProcessErrorResponse,
  8. type HostAgentProcessExceptionResponse,
  9. type HostAgentProcessExitedResponse,
  10. type HostAgentProcessReadyResponse,
  11. type HostAgentProcessSpawnedResponse,
  12. } from "@zcode/shared";
  13. import {
  14. createAgentCrashFingerprint,
  15. parseAgentProcessExitDiagnostic,
  16. parseAgentProcessSpawnDiagnostic,
  17. sanitizeAgentCrashDetail,
  18. } from "@zcode/shared/agent-crash-diagnostic";
  19. import type { CrashCapturePaths } from "./desktopCrashCapture.js";
  20. import { registerCrashEventMonitor as registerBaseCrashEventMonitor } from "./desktopCrashCapture.js";
  21. import { getResourceManagerWindowId } from "./resourceManagerWindow.js";
  22. /** ANR:主线程无响应阈值(与 Electron unresponsive 对齐) */
  23. export const STABILITY_ANR_THRESHOLD_MS = 5_000;
  24. /** 挂死:未恢复且未 crash 的更长无响应阈值 */
  25. export const STABILITY_FREEZE_THRESHOLD_MS = 30_000;
  26. export const STABILITY_TELEMETRY_SCHEMA_VERSION = 2;
  27. const WINDOWS_CONTROLLED_TERMINATION_EXIT_CODE = 0x40010004;
  28. const AGENT_EXCEPTION_DEDUP_CAPACITY = 1024;
  29. const reportedAgentExceptions = new Set<string>();
  30. export type StabilityLifecycleScene = "cold_start" | "runtime" | "app_quit" | "update_install";
  31. export type StabilityWindowScene = "main" | "process_monitor" | "other";
  32. export type StabilityCrashKind = "native" | "js" | "oom";
  33. export type StabilityCrashScope =
  34. | "app_native_process"
  35. | "main_window_renderer"
  36. | "auxiliary_window_renderer"
  37. | "embedded_webview"
  38. | "host"
  39. | "child";
  40. export type StabilityCrashCause =
  41. | "oom"
  42. | "process_crashed"
  43. | "abnormal_exit"
  44. | "launch_failed"
  45. | "integrity_failure"
  46. | "native_crash"
  47. | "unknown";
  48. export interface StabilityCrashClassification {
  49. crashKind: StabilityCrashKind;
  50. crashScope: StabilityCrashScope;
  51. crashCause: StabilityCrashCause;
  52. }
  53. export type StabilityProcessRole =
  54. | "main"
  55. | "renderer"
  56. | "gpu"
  57. | "utility"
  58. | "agent"
  59. | "host"
  60. | "child"
  61. | "unknown";
  62. export type AgentCrashPhase = "startup" | "runtime" | "unknown";
  63. export type AgentTerminationClass = "exit_zero" | "exit_nonzero" | "signal" | "unknown";
  64. interface StabilityLogger {
  65. info: (...args: unknown[]) => void;
  66. warn: (...args: unknown[]) => void;
  67. error: (...args: unknown[]) => void;
  68. debug?: (...args: unknown[]) => void;
  69. }
  70. interface StabilityGlobalContext {
  71. deviceMid: string;
  72. platform: NodeJS.Platform;
  73. appVersion: string;
  74. armsEnv: ReturnType<typeof mapZCodeEnvToArmsRumEnv>;
  75. }
  76. interface UnresponsiveWatchState {
  77. windowId: number;
  78. webContentsId: number;
  79. windowScene: StabilityWindowScene;
  80. startedAt: number;
  81. anrReported: boolean;
  82. freezeReported: boolean;
  83. crashReported: boolean;
  84. pollTimer: ReturnType<typeof setTimeout> | null;
  85. }
  86. export interface RenderProcessGoneInput {
  87. reason: string;
  88. exitCode: number;
  89. webContentsType: string;
  90. windowScene?: StabilityWindowScene;
  91. }
  92. export interface ChildProcessGoneInput {
  93. type: string;
  94. reason: string;
  95. exitCode: number;
  96. serviceName?: string;
  97. name: string;
  98. }
  99. let globalContext: StabilityGlobalContext | null = null;
  100. let lifecycleScene: StabilityLifecycleScene = "runtime";
  101. // 修复原因:WebContents.getType() 对所有 BrowserWindow 都返回 window,无法区分主业务窗和
  102. // Resource Manager / 更新 / About。只登记 createWindowInstance 创建的业务窗口,避免辅助窗污染 Crash 率。
  103. const mainWindowIds = new Set<number>();
  104. let perfAppStartReported = false;
  105. const unresponsiveByWebContentsId = new Map<number, UnresponsiveWatchState>();
  106. function normalizeOsCategory(platform: NodeJS.Platform): string {
  107. switch (platform) {
  108. case "darwin":
  109. return "macos";
  110. case "win32":
  111. return "windows";
  112. default:
  113. return "linux";
  114. }
  115. }
  116. function stringifyProperties(
  117. properties: Record<string, string | number | boolean | undefined>,
  118. ): Record<string, string> {
  119. const result: Record<string, string> = {};
  120. for (const [key, value] of Object.entries(properties)) {
  121. if (value === undefined) {
  122. continue;
  123. }
  124. result[key] = String(value);
  125. }
  126. return result;
  127. }
  128. function resolveStabilityMetricValue(
  129. name: string,
  130. properties: Record<string, string | number | boolean | undefined>,
  131. ): number {
  132. switch (name) {
  133. case "perf_anr":
  134. case "perf_freeze": {
  135. const duration = Number(properties.duration_ms);
  136. return Number.isFinite(duration) ? duration : 0;
  137. }
  138. case "perf_app_exit":
  139. case "perf_process_exit": {
  140. const exitCode = Number(properties.exit_code);
  141. return Number.isFinite(exitCode) ? exitCode : 0;
  142. }
  143. case "perf_crash":
  144. return 1;
  145. case "perf_app_start":
  146. default:
  147. return 1;
  148. }
  149. }
  150. function classifyAgentCrashPhase(runtimeReady: boolean | undefined): AgentCrashPhase {
  151. if (runtimeReady === true) {
  152. return "runtime";
  153. }
  154. if (runtimeReady === false) {
  155. return "startup";
  156. }
  157. return "unknown";
  158. }
  159. function classifyAgentTermination(event: HostAgentProcessExitedResponse): AgentTerminationClass {
  160. if (event.signal) {
  161. return "signal";
  162. }
  163. if (event.exitCode === 0) {
  164. return "exit_zero";
  165. }
  166. if (typeof event.exitCode === "number") {
  167. return "exit_nonzero";
  168. }
  169. return "unknown";
  170. }
  171. function reportStabilityCustom(
  172. name: string,
  173. properties: Record<string, string | number | boolean | undefined>,
  174. windowScene?: StabilityWindowScene,
  175. lifecycleSceneOverride?: StabilityLifecycleScene,
  176. ): void {
  177. if (!globalContext) {
  178. return;
  179. }
  180. const metricValue = resolveStabilityMetricValue(name, properties);
  181. const payload = stringifyProperties({
  182. event_name: name,
  183. platform: normalizeOsCategory(globalContext.platform),
  184. app_version: globalContext.appVersion,
  185. arms_env: globalContext.armsEnv,
  186. device_mid: globalContext.deviceMid,
  187. telemetry_schema_version: STABILITY_TELEMETRY_SCHEMA_VERSION,
  188. scene_lifecycle: lifecycleSceneOverride ?? lifecycleScene,
  189. scene_window: windowScene ?? "main",
  190. metric_value: metricValue,
  191. ...properties,
  192. });
  193. try {
  194. // ARMS 原始日志/控制台按 custom 类型展示;业务分组用 group
  195. // value 填具体数值:ANR/挂死为 duration_ms,退出为 exit_code,计数类统一为 1
  196. armsRum.sendCustom({
  197. name,
  198. type: "custom",
  199. group: "stability",
  200. value: metricValue,
  201. properties: payload,
  202. });
  203. } catch (error) {
  204. // 稳定性上报失败不应影响主流程
  205. console.warn("[stability] sendCustom failed:", name, error);
  206. }
  207. }
  208. export function reportAgentProcessExceptionToArms(
  209. event: HostAgentProcessExceptionResponse,
  210. logger: StabilityLogger,
  211. ): void {
  212. if (!globalContext) return;
  213. const key = `${event.runtimeInstanceId}:${event.diagnostic.errorId}`;
  214. if (reportedAgentExceptions.has(key)) return;
  215. const diagnostic = event.diagnostic;
  216. const name = sanitizeAgentCrashDetail(diagnostic.name, event.workspacePath);
  217. const message = sanitizeAgentCrashDetail(diagnostic.message, event.workspacePath);
  218. const stack =
  219. diagnostic.stack === undefined
  220. ? undefined
  221. : sanitizeAgentCrashDetail(diagnostic.stack, event.workspacePath);
  222. try {
  223. // 根因:Electron collector 只监听自身进程,CLI 异常必须携带原始栈显式发送,
  224. // 不能先转成 console.error 包装字符串,也不能等待进程退出后再上报。
  225. armsRum.sendEvent({
  226. event_type: "exception",
  227. type: "error",
  228. source: diagnostic.kind,
  229. name,
  230. message,
  231. ...(stack === undefined ? {} : { stack }),
  232. timestamp: diagnostic.occurredAt,
  233. properties: stringifyProperties({
  234. process_role: "agent",
  235. process_error_kind: diagnostic.kind,
  236. process_error_origin: diagnostic.origin,
  237. error_id: diagnostic.errorId,
  238. runtime_instance_id: event.runtimeInstanceId,
  239. runtime_generation: event.runtimeGeneration,
  240. provider: event.provider,
  241. lane: event.lane,
  242. error_fingerprint: createAgentCrashFingerprint([
  243. name,
  244. message,
  245. stack?.split(/\r?\n/).find((line) => line.trim().startsWith("at ")) ?? "",
  246. ]),
  247. app_version: globalContext.appVersion,
  248. arms_env: globalContext.armsEnv,
  249. device_mid: globalContext.deviceMid,
  250. platform: normalizeOsCategory(globalContext.platform),
  251. }),
  252. });
  253. reportedAgentExceptions.add(key);
  254. if (reportedAgentExceptions.size > AGENT_EXCEPTION_DEDUP_CAPACITY) {
  255. reportedAgentExceptions.delete(reportedAgentExceptions.values().next().value!);
  256. }
  257. } catch (error) {
  258. // SDK 失败不能影响 Host 消息处理;未成功提交的事件不进入去重集合。
  259. logger.warn("[stability] Agent exception report failed", error);
  260. }
  261. }
  262. export function reportAgentProcessStartToArms(
  263. event: HostAgentProcessSpawnedResponse,
  264. logger: StabilityLogger,
  265. ): void {
  266. reportStabilityCustom("perf_agent_start", {
  267. process_role: "agent",
  268. // mcp-status 与 plugin lane 进程共用 cwd/command,只有 lane 能区分事件来源。
  269. ...(event.lane ? { lane: event.lane } : {}),
  270. provider: event.provider,
  271. runtime_generation: event.runtimeGeneration,
  272. runtime_instance_id: event.runtimeInstanceId,
  273. });
  274. logger.info("[stability] perf_agent_start reported", {
  275. pid: event.pid,
  276. runtimeGeneration: event.runtimeGeneration,
  277. runtimeInstanceId: event.runtimeInstanceId,
  278. });
  279. }
  280. export function reportAgentProcessReadyToArms(
  281. event: HostAgentProcessReadyResponse,
  282. logger: StabilityLogger,
  283. ): void {
  284. reportStabilityCustom("perf_agent_ready", {
  285. process_role: "agent",
  286. // mcp-status 与 plugin lane 进程共用 cwd/command,只有 lane 能区分事件来源。
  287. ...(event.lane ? { lane: event.lane } : {}),
  288. provider: event.provider,
  289. runtime_generation: event.runtimeGeneration,
  290. runtime_instance_id: event.runtimeInstanceId,
  291. startup_duration_ms: event.startupDurationMs,
  292. });
  293. logger.info("[stability] perf_agent_ready reported", {
  294. pid: event.pid,
  295. runtimeGeneration: event.runtimeGeneration,
  296. runtimeInstanceId: event.runtimeInstanceId,
  297. startupDurationMs: event.startupDurationMs,
  298. });
  299. }
  300. export function reportAgentProcessExitToArms(
  301. event: HostAgentProcessExitedResponse,
  302. logger: StabilityLogger,
  303. ): void {
  304. if (event.terminationKind !== "unexpected") {
  305. return;
  306. }
  307. const isProtocolFailure = event.terminationReason === "protocol-close";
  308. if (
  309. !isProtocolFailure &&
  310. (event.exitCode === WINDOWS_CONTROLLED_TERMINATION_EXIT_CODE || event.signal === "SIGTERM")
  311. ) {
  312. // Bug 根因:协议故障会先触发 protocol-close,再由 Host 回收仍存活的进程,
  313. // 因此最终也可能表现为 SIGTERM / Windows control-c exit code。只有缺少结构化
  314. // 协议根因时,裸退出签名才不足以证明 Agent 自身崩溃,应继续抑制误报。
  315. logger.debug?.("[stability] controlled Agent termination suppressed", {
  316. pid: event.pid,
  317. runtimeInstanceId: event.runtimeInstanceId,
  318. exitCode: event.exitCode,
  319. signal: event.signal,
  320. });
  321. return;
  322. }
  323. if (lifecycleScene === "app_quit" || lifecycleScene === "update_install") {
  324. // Bug 根因:Host 清理与 IPC 回传是异步的,perf_app_exit 之后仍可能晚到一个缺失
  325. // termination intent 的 Agent exit。应用退出是 main 持有的更高层事实,不能计入 runtime crash。
  326. logger.debug?.("[stability] late Agent exit suppressed during app shutdown", {
  327. pid: event.pid,
  328. runtimeInstanceId: event.runtimeInstanceId,
  329. lifecycleScene,
  330. });
  331. return;
  332. }
  333. const diagnostic = parseAgentProcessExitDiagnostic(event);
  334. reportStabilityCustom("perf_agent_crash", {
  335. process_role: "agent",
  336. // mcp-status 与 plugin lane 进程共用 cwd/command,只有 lane 能区分事件来源。
  337. ...(event.lane ? { lane: event.lane } : {}),
  338. incident_kind: "unexpected_exit",
  339. provider: event.provider,
  340. exit_code: event.exitCode ?? "",
  341. signal: event.signal ?? "",
  342. runtime_generation: event.runtimeGeneration,
  343. runtime_instance_id: event.runtimeInstanceId,
  344. uptime_ms: event.uptimeMs,
  345. stderr_line_count: event.stderrLineCount,
  346. crash_phase: classifyAgentCrashPhase(event.runtimeReady),
  347. termination_class: classifyAgentTermination(event),
  348. termination_reason: event.terminationReason,
  349. diagnostic_class: diagnostic.diagnosticClass,
  350. error_name: diagnostic.errorName,
  351. error_code: diagnostic.errorCode,
  352. error_message: diagnostic.errorMessage,
  353. error_stack: diagnostic.errorStack,
  354. error_fingerprint: diagnostic.errorFingerprint,
  355. });
  356. // 上报成功属于观测日志,error 会被 console collector 再生成一条伪 JS 异常。
  357. logger.info("[stability] perf_agent_crash reported", {
  358. pid: event.pid,
  359. exitCode: event.exitCode,
  360. signal: event.signal,
  361. runtimeGeneration: event.runtimeGeneration,
  362. errorName: diagnostic.errorName,
  363. errorCode: diagnostic.errorCode,
  364. errorFingerprint: diagnostic.errorFingerprint,
  365. });
  366. }
  367. export function reportAgentProcessSpawnErrorToArms(
  368. event: HostAgentProcessErrorResponse,
  369. logger: StabilityLogger,
  370. ): void {
  371. const diagnostic = parseAgentProcessSpawnDiagnostic(event);
  372. reportStabilityCustom("perf_agent_spawn_error", {
  373. process_role: "agent",
  374. // mcp-status 与 plugin lane 进程共用 cwd/command,只有 lane 能区分事件来源。
  375. ...(event.lane ? { lane: event.lane } : {}),
  376. incident_kind: "spawn_error",
  377. provider: event.provider,
  378. runtime_generation: event.runtimeGeneration,
  379. runtime_instance_id: event.runtimeInstanceId,
  380. diagnostic_class: diagnostic.diagnosticClass,
  381. error_name: diagnostic.errorName,
  382. error_code: diagnostic.errorCode,
  383. error_message: diagnostic.errorMessage,
  384. error_stack: diagnostic.errorStack,
  385. error_fingerprint: diagnostic.errorFingerprint,
  386. });
  387. logger.info("[stability] perf_agent_spawn_error reported", {
  388. pid: event.pid,
  389. runtimeGeneration: event.runtimeGeneration,
  390. errorName: diagnostic.errorName,
  391. errorCode: diagnostic.errorCode,
  392. errorFingerprint: diagnostic.errorFingerprint,
  393. });
  394. }
  395. export function mapRenderProcessGoneToCrashKind(
  396. input: RenderProcessGoneInput,
  397. ): StabilityCrashKind | null {
  398. return classifyRenderProcessCrash(input)?.crashKind ?? null;
  399. }
  400. function mapExitReasonToCrashKind(reason: string): StabilityCrashKind {
  401. // Electron 的 renderer/child gone 回调共用这组退出原因,OOM 不能因进程来源不同而被归为 native。
  402. return reason === "oom" || reason === "memory-eviction" ? "oom" : "native";
  403. }
  404. function mapExitReasonToCrashCause(reason: string): StabilityCrashCause {
  405. switch (reason) {
  406. case "oom":
  407. // Electron 41 将 Chromium 的内存压力驱逐单独命名;它与 oom 一样表示进程因内存
  408. // 压力退出,不能落入 native/unknown,否则 OOM 指标会被低估。
  409. case "memory-eviction":
  410. return "oom";
  411. case "crashed":
  412. return "process_crashed";
  413. case "abnormal":
  414. case "abnormal-exit":
  415. return "abnormal_exit";
  416. case "launch-failed":
  417. return "launch_failed";
  418. case "integrity-failure":
  419. return "integrity_failure";
  420. default:
  421. return "unknown";
  422. }
  423. }
  424. export function classifyRenderProcessCrash(
  425. input: RenderProcessGoneInput,
  426. ): StabilityCrashClassification | null {
  427. if (input.reason === "killed" || input.reason === "clean-exit") {
  428. return null;
  429. }
  430. return {
  431. crashKind: mapExitReasonToCrashKind(input.reason),
  432. crashScope:
  433. input.webContentsType === "webview"
  434. ? "embedded_webview"
  435. : input.windowScene === undefined || input.windowScene === "main"
  436. ? "main_window_renderer"
  437. : "auxiliary_window_renderer",
  438. crashCause: mapExitReasonToCrashCause(input.reason),
  439. };
  440. }
  441. export function mapChildProcessGoneToProcessRole(
  442. type: string,
  443. processName?: string,
  444. ): StabilityProcessRole {
  445. return mapChildProcessGoneToProcessRoleWithName(type, processName);
  446. }
  447. function mapChildProcessGoneToProcessRoleWithName(
  448. type: string,
  449. processName?: string,
  450. ): StabilityProcessRole {
  451. if (processName?.startsWith("zcode-host")) {
  452. return "host";
  453. }
  454. if (processName?.startsWith("zcode-agent")) {
  455. return "agent";
  456. }
  457. switch (type) {
  458. case "GPU":
  459. return "gpu";
  460. case "Utility":
  461. return "utility";
  462. default:
  463. return "child";
  464. }
  465. }
  466. export function shouldReportChildProcessGoneAsCrash(input: ChildProcessGoneInput): boolean {
  467. if (input.reason === "killed" || input.reason === "clean-exit") {
  468. return false;
  469. }
  470. const role = mapChildProcessGoneToProcessRoleWithName(input.type, input.name);
  471. if (role === "gpu") {
  472. return false;
  473. }
  474. // Bugfix: RUM 里 Video Capture / Network Service / Audio Service 等 Chromium Utility
  475. // 子进程会被系统自动重建,不会让 ZCode 主窗口或会话不可用;它们只能作为可恢复退出记录,
  476. // 不能进入 perf_crash,否则会把 crash-free 指标按“非真实崩溃”拉低。
  477. if (role === "utility") {
  478. return false;
  479. }
  480. return true;
  481. }
  482. export function shouldReportAnr(elapsedMs: number, anrReported: boolean): boolean {
  483. return !anrReported && elapsedMs >= STABILITY_ANR_THRESHOLD_MS;
  484. }
  485. export function shouldReportFreeze(
  486. elapsedMs: number,
  487. freezeReported: boolean,
  488. crashReported: boolean,
  489. ): boolean {
  490. return !freezeReported && !crashReported && elapsedMs >= STABILITY_FREEZE_THRESHOLD_MS;
  491. }
  492. function resolveRegisteredWindowScene(win: BrowserWindow | null | undefined): StabilityWindowScene {
  493. if (!win || win.isDestroyed()) {
  494. return "other";
  495. }
  496. const resourceManagerId = getResourceManagerWindowId();
  497. if (resourceManagerId != null && win.id === resourceManagerId) {
  498. return "process_monitor";
  499. }
  500. return mainWindowIds.has(win.id) ? "main" : "other";
  501. }
  502. function resolveWindowScene(win: BrowserWindow | null | undefined): StabilityWindowScene {
  503. if (win && !win.isDestroyed()) {
  504. return resolveRegisteredWindowScene(win);
  505. }
  506. const focused = BrowserWindow.getFocusedWindow();
  507. return focused && !focused.isDestroyed() ? resolveRegisteredWindowScene(focused) : "main";
  508. }
  509. function markWebContentsCrash(webContentsId: number): void {
  510. const state = unresponsiveByWebContentsId.get(webContentsId);
  511. if (state) {
  512. state.crashReported = true;
  513. if (state.pollTimer) {
  514. clearTimeout(state.pollTimer);
  515. state.pollTimer = null;
  516. }
  517. }
  518. }
  519. function clearUnresponsiveWatch(webContentsId: number): void {
  520. const state = unresponsiveByWebContentsId.get(webContentsId);
  521. if (!state) {
  522. return;
  523. }
  524. if (state.pollTimer) {
  525. clearTimeout(state.pollTimer);
  526. }
  527. unresponsiveByWebContentsId.delete(webContentsId);
  528. }
  529. function pollUnresponsiveState(state: UnresponsiveWatchState, logger: StabilityLogger): void {
  530. if (state.crashReported) {
  531. clearUnresponsiveWatch(state.webContentsId);
  532. return;
  533. }
  534. const elapsedMs = Date.now() - state.startedAt;
  535. const windowScene = state.windowScene;
  536. if (shouldReportAnr(elapsedMs, state.anrReported)) {
  537. state.anrReported = true;
  538. reportStabilityCustom(
  539. "perf_anr",
  540. {
  541. duration_ms: elapsedMs,
  542. window_id: state.windowId,
  543. web_contents_id: state.webContentsId,
  544. },
  545. windowScene,
  546. );
  547. logger.warn("[stability] perf_anr reported", {
  548. windowId: state.windowId,
  549. webContentsId: state.webContentsId,
  550. durationMs: elapsedMs,
  551. });
  552. }
  553. if (shouldReportFreeze(elapsedMs, state.freezeReported, state.crashReported)) {
  554. state.freezeReported = true;
  555. reportStabilityCustom(
  556. "perf_freeze",
  557. {
  558. duration_ms: elapsedMs,
  559. window_id: state.windowId,
  560. web_contents_id: state.webContentsId,
  561. },
  562. windowScene,
  563. );
  564. logger.warn("[stability] perf_freeze reported", {
  565. windowId: state.windowId,
  566. webContentsId: state.webContentsId,
  567. durationMs: elapsedMs,
  568. });
  569. }
  570. if (!state.freezeReported && !state.crashReported) {
  571. state.pollTimer = setTimeout(() => pollUnresponsiveState(state, logger), 1_000);
  572. state.pollTimer.unref?.();
  573. }
  574. }
  575. function attachWebContentsStabilityWatch(
  576. win: BrowserWindow,
  577. webContents: WebContents,
  578. logger: StabilityLogger,
  579. ): void {
  580. const webContentsId = webContents.id;
  581. webContents.on("unresponsive", () => {
  582. clearUnresponsiveWatch(webContentsId);
  583. const state: UnresponsiveWatchState = {
  584. windowId: win.id,
  585. webContentsId,
  586. windowScene: resolveRegisteredWindowScene(win),
  587. startedAt: Date.now(),
  588. anrReported: false,
  589. freezeReported: false,
  590. crashReported: false,
  591. pollTimer: null,
  592. };
  593. unresponsiveByWebContentsId.set(webContentsId, state);
  594. logger.warn("[stability] webContents unresponsive", {
  595. windowId: win.id,
  596. webContentsId,
  597. url: webContents.getURL(),
  598. });
  599. pollUnresponsiveState(state, logger);
  600. });
  601. webContents.on("responsive", () => {
  602. logger.info("[stability] webContents responsive", {
  603. windowId: win.id,
  604. webContentsId,
  605. });
  606. clearUnresponsiveWatch(webContentsId);
  607. });
  608. webContents.on("destroyed", () => {
  609. clearUnresponsiveWatch(webContentsId);
  610. });
  611. }
  612. export function configureDesktopStabilityTelemetry(context: StabilityGlobalContext): void {
  613. globalContext = context;
  614. armsRum.setConfig("properties", {
  615. device_mid: context.deviceMid,
  616. platform: normalizeOsCategory(context.platform),
  617. app_version: context.appVersion,
  618. arms_env: context.armsEnv,
  619. });
  620. }
  621. /** 与 @arms/rum-electron pv-collector 的 initial_load 窗口对齐,避免早于首屏 PV 单独 flush */
  622. const PERF_APP_START_AFTER_VIEW_MS = 3_200;
  623. export function reportPerfAppStart(logger: StabilityLogger): void {
  624. if (perfAppStartReported) {
  625. return;
  626. }
  627. perfAppStartReported = true;
  628. // 延迟启动埋点可能晚于退出准备;只覆盖事件字段,不能把已确认的退出状态改回 runtime。
  629. reportStabilityCustom("perf_app_start", {}, "main", "cold_start");
  630. logger.info("[stability] perf_app_start reported");
  631. }
  632. /**
  633. * 在主窗口首屏加载完成后再上报 perf_app_start。
  634. * 原因:过早 sendCustom 时 view 仍为 __default__,且可能与 renderer PV 分属不同上报批次;
  635. * ARMS 原始日志里常见只有 PV、看不到同 session 的 custom。
  636. */
  637. export function scheduleReportPerfAppStartAfterMainViewReady(
  638. webContents: WebContents,
  639. logger: StabilityLogger,
  640. ): void {
  641. if (perfAppStartReported || webContents.isDestroyed()) {
  642. return;
  643. }
  644. const reportAfterView = (): void => {
  645. if (perfAppStartReported || webContents.isDestroyed()) {
  646. return;
  647. }
  648. setTimeout(() => {
  649. if (!webContents.isDestroyed()) {
  650. reportPerfAppStart(logger);
  651. }
  652. }, PERF_APP_START_AFTER_VIEW_MS);
  653. };
  654. if (webContents.isLoading()) {
  655. webContents.once("did-finish-load", reportAfterView);
  656. return;
  657. }
  658. reportAfterView();
  659. }
  660. export function registerStabilityMainWindow(win: BrowserWindow): void {
  661. if (win.isDestroyed() || mainWindowIds.has(win.id)) {
  662. return;
  663. }
  664. mainWindowIds.add(win.id);
  665. win.once("closed", () => {
  666. mainWindowIds.delete(win.id);
  667. });
  668. }
  669. export function notifyStabilityLifecycle(scene: StabilityLifecycleScene): void {
  670. lifecycleScene = scene;
  671. }
  672. export function getStabilityLifecycleScene(): StabilityLifecycleScene {
  673. return lifecycleScene;
  674. }
  675. export function notifyStabilityAppExit(
  676. scene: StabilityLifecycleScene,
  677. logger: StabilityLogger,
  678. options?: { exitCode?: number; exitKind?: string },
  679. ): void {
  680. // Bug 根因:旧实现上报 perf_app_exit 后立即恢复 runtime;Agent/Host 的异步退出事件
  681. // 因而丢失 app_quit/update_install 边界并被误计为 crash。退出流程一旦开始就不可逆,
  682. // lifecycle 必须保持到主进程终止。
  683. lifecycleScene = scene;
  684. reportStabilityCustom("perf_app_exit", {
  685. exit_code: options?.exitCode ?? 0,
  686. exit_kind: options?.exitKind ?? "normal",
  687. });
  688. logger.info("[stability] perf_app_exit reported", { scene, exitCode: options?.exitCode ?? 0 });
  689. }
  690. function reportPerfCrash(
  691. classification: StabilityCrashClassification,
  692. logger: StabilityLogger,
  693. properties: Record<string, string | number | boolean | undefined>,
  694. win?: BrowserWindow | null,
  695. ): void {
  696. const crashProperties = {
  697. crash_id: randomUUID(),
  698. crash_kind: classification.crashKind,
  699. crash_scope: classification.crashScope,
  700. crash_cause: classification.crashCause,
  701. crash_source: "electron_callback",
  702. ...properties,
  703. };
  704. // Bugfix: 旧实现按 crash_kind 做五分钟去重,会吞掉同类但不同进程的真实事故。
  705. // Electron 的 gone 回调本身就是单次事故边界,这里每个回调只上报一次。
  706. reportStabilityCustom("perf_crash", crashProperties, resolveWindowScene(win));
  707. logger.error("[stability] perf_crash reported", crashProperties);
  708. }
  709. function reportPerfProcessExit(
  710. logger: StabilityLogger,
  711. properties: Record<string, string | number | boolean | undefined>,
  712. win?: BrowserWindow | null,
  713. ): void {
  714. reportStabilityCustom("perf_process_exit", properties, resolveWindowScene(win));
  715. // Bug 原因:perf_process_exit 同时承载受控退出和可恢复的 helper 异常退出。
  716. // 旧实现统一使用 error,导致正常生命周期被 ARMS console collector 误计为异常。
  717. const logLevel = properties.exit_kind === "normal" ? "info" : "warn";
  718. logger[logLevel]("[stability] perf_process_exit reported", properties);
  719. }
  720. export function registerDesktopStabilityMonitors(
  721. logger: StabilityLogger,
  722. crashPaths: CrashCapturePaths,
  723. ): void {
  724. registerBaseCrashEventMonitor(logger, crashPaths, {
  725. onRenderProcessGone: (webContents, details) => {
  726. markWebContentsCrash(webContents.id);
  727. const win = BrowserWindow.fromWebContents(webContents);
  728. const input: RenderProcessGoneInput = {
  729. reason: details.reason,
  730. exitCode: details.exitCode,
  731. webContentsType: webContents.getType(),
  732. // 必须使用崩溃 WebContents 自身所属窗口;回退到当前焦点窗会把辅助窗误判成主业务窗。
  733. windowScene: resolveRegisteredWindowScene(win),
  734. };
  735. const classification = classifyRenderProcessCrash(input);
  736. if (classification) {
  737. reportPerfCrash(
  738. classification,
  739. logger,
  740. {
  741. exit_code: details.exitCode,
  742. exit_reason: details.reason,
  743. process_role: "renderer",
  744. web_contents_type: webContents.getType(),
  745. web_contents_id: webContents.id,
  746. window_id: win?.id,
  747. },
  748. win,
  749. );
  750. } else {
  751. reportPerfProcessExit(
  752. logger,
  753. {
  754. exit_code: details.exitCode,
  755. exit_reason: details.reason,
  756. process_role: "renderer",
  757. exit_kind: "normal",
  758. web_contents_id: webContents.id,
  759. },
  760. win,
  761. );
  762. }
  763. },
  764. onChildProcessGone: (details) => {
  765. // 修复原因:Electron 将 utilityProcess.fork() 的自定义标识放在 serviceName,
  766. // name 只表示 Chromium Utility 服务名(如 Network Service)。只读 name 会把
  767. // Host 归为 utility,导致 Host 异常退出走 recoverable_child_crash 而不是 perf_crash。
  768. const processName = details.serviceName?.trim() || details.name?.trim() || "";
  769. const role = mapChildProcessGoneToProcessRoleWithName(details.type, processName);
  770. if (details.reason === "killed" || details.reason === "clean-exit") {
  771. reportPerfProcessExit(logger, {
  772. exit_code: details.exitCode,
  773. exit_reason: details.reason,
  774. process_role: role,
  775. exit_kind: "normal",
  776. process_type: details.type,
  777. process_name: processName,
  778. });
  779. } else if (!shouldReportChildProcessGoneAsCrash({ ...details, name: processName })) {
  780. reportPerfProcessExit(logger, {
  781. exit_code: details.exitCode,
  782. exit_reason: details.reason,
  783. process_role: role,
  784. exit_kind: "recoverable_child_crash",
  785. process_type: details.type,
  786. process_name: processName,
  787. });
  788. } else {
  789. reportPerfCrash(
  790. {
  791. crashKind: mapExitReasonToCrashKind(details.reason),
  792. crashScope: role === "host" ? "host" : "child",
  793. crashCause: mapExitReasonToCrashCause(details.reason),
  794. },
  795. logger,
  796. {
  797. exit_code: details.exitCode,
  798. exit_reason: details.reason,
  799. process_role: role,
  800. process_type: details.type,
  801. process_name: processName,
  802. },
  803. );
  804. }
  805. },
  806. onBrowserWindowCreated: (win) => {
  807. attachWebContentsStabilityWatch(win, win.webContents, logger);
  808. },
  809. });
  810. }