desktopStabilityTelemetry.test.ts 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  1. import { beforeEach, describe, expect, it, vi } from "vitest";
  2. const sendCustom = vi.fn();
  3. const setConfig = vi.fn();
  4. const registerCrashEventMonitor = vi.fn();
  5. const fromWebContents = vi.fn(() => null as unknown);
  6. const getResourceManagerWindowId = vi.fn(() => null as number | null);
  7. // Bugfix: 这些断言覆盖稳定性上报的纯映射与阈值逻辑,不需要真实 Electron/main 依赖。
  8. // 全量单测里真实 Electron 入口首次加载可能超过 5s,导致无关运行时成本压垮纯函数测试。
  9. vi.mock("electron", () => ({
  10. BrowserWindow: {
  11. fromWebContents,
  12. getFocusedWindow: vi.fn(() => null),
  13. },
  14. }));
  15. vi.mock("@arms/rum-electron", () => ({
  16. default: {
  17. sendCustom,
  18. setConfig,
  19. },
  20. }));
  21. vi.mock("@zcode/shared", () => ({
  22. mapZCodeEnvToArmsRumEnv: vi.fn(() => "local"),
  23. }));
  24. vi.mock("../src/main/desktopCrashCapture.js", () => ({
  25. registerCrashEventMonitor,
  26. }));
  27. vi.mock("../src/main/resourceManagerWindow.js", () => ({
  28. getResourceManagerWindowId,
  29. }));
  30. describe("desktopStabilityTelemetry", () => {
  31. beforeEach(() => {
  32. sendCustom.mockClear();
  33. setConfig.mockClear();
  34. registerCrashEventMonitor.mockClear();
  35. fromWebContents.mockReset();
  36. fromWebContents.mockReturnValue(null);
  37. getResourceManagerWindowId.mockReset();
  38. getResourceManagerWindowId.mockReturnValue(null);
  39. vi.resetModules();
  40. });
  41. describe("classifyRenderProcessCrash", () => {
  42. it("separates the crashed surface from the crash cause", async () => {
  43. const { classifyRenderProcessCrash } =
  44. await import("../src/main/desktopStabilityTelemetry.js");
  45. expect(
  46. classifyRenderProcessCrash({
  47. reason: "oom",
  48. exitCode: -1,
  49. webContentsType: "webview",
  50. }),
  51. ).toEqual({
  52. crashKind: "oom",
  53. crashScope: "embedded_webview",
  54. crashCause: "oom",
  55. });
  56. expect(
  57. classifyRenderProcessCrash({
  58. reason: "crashed",
  59. exitCode: 1,
  60. webContentsType: "window",
  61. }),
  62. ).toEqual({
  63. crashKind: "native",
  64. crashScope: "main_window_renderer",
  65. crashCause: "process_crashed",
  66. });
  67. });
  68. it("returns null for killed and clean-exit", async () => {
  69. const { classifyRenderProcessCrash } =
  70. await import("../src/main/desktopStabilityTelemetry.js");
  71. expect(
  72. classifyRenderProcessCrash({
  73. reason: "killed",
  74. exitCode: 0,
  75. webContentsType: "renderer",
  76. }),
  77. ).toBeNull();
  78. expect(
  79. classifyRenderProcessCrash({
  80. reason: "clean-exit",
  81. exitCode: 0,
  82. webContentsType: "renderer",
  83. }),
  84. ).toBeNull();
  85. });
  86. it("maps all non-OOM process crashes to native instead of calling them JS errors", async () => {
  87. const { classifyRenderProcessCrash } =
  88. await import("../src/main/desktopStabilityTelemetry.js");
  89. expect(
  90. classifyRenderProcessCrash({
  91. reason: "abnormal-exit",
  92. exitCode: 1,
  93. webContentsType: "renderer",
  94. }),
  95. ).toEqual({
  96. crashKind: "native",
  97. crashScope: "main_window_renderer",
  98. crashCause: "abnormal_exit",
  99. });
  100. });
  101. it("classifies memory eviction as an OOM crash", async () => {
  102. const { classifyRenderProcessCrash } =
  103. await import("../src/main/desktopStabilityTelemetry.js");
  104. expect(
  105. classifyRenderProcessCrash({
  106. reason: "memory-eviction",
  107. exitCode: 137,
  108. webContentsType: "window",
  109. }),
  110. ).toEqual({
  111. crashKind: "oom",
  112. crashScope: "main_window_renderer",
  113. crashCause: "oom",
  114. });
  115. });
  116. });
  117. it("reports each crash callback once with count semantics and schema-v2 dimensions", async () => {
  118. const {
  119. configureDesktopStabilityTelemetry,
  120. registerDesktopStabilityMonitors,
  121. registerStabilityMainWindow,
  122. } = await import("../src/main/desktopStabilityTelemetry.js");
  123. configureDesktopStabilityTelemetry({
  124. deviceMid: "test-device",
  125. platform: "darwin",
  126. appVersion: "0.0.0-test",
  127. armsEnv: "local",
  128. });
  129. const logger = {
  130. info: vi.fn(),
  131. warn: vi.fn(),
  132. error: vi.fn(),
  133. debug: vi.fn(),
  134. };
  135. const mainWindow = {
  136. id: 101,
  137. isDestroyed: () => false,
  138. once: vi.fn(),
  139. };
  140. const auxiliaryWindow = {
  141. id: 102,
  142. isDestroyed: () => false,
  143. once: vi.fn(),
  144. };
  145. registerStabilityMainWindow(mainWindow as never);
  146. getResourceManagerWindowId.mockReturnValue(auxiliaryWindow.id);
  147. fromWebContents.mockImplementation((webContents: unknown) =>
  148. (webContents as { id: number }).id === 11 ? mainWindow : auxiliaryWindow,
  149. );
  150. registerDesktopStabilityMonitors(logger, {} as never);
  151. const hooks = registerCrashEventMonitor.mock.calls[0]?.[2] as {
  152. onRenderProcessGone: (
  153. webContents: {
  154. id: number;
  155. getType: () => string;
  156. },
  157. details: { reason: string; exitCode: number },
  158. ) => void;
  159. };
  160. hooks.onRenderProcessGone(
  161. { id: 11, getType: () => "window" },
  162. { reason: "crashed", exitCode: 139 },
  163. );
  164. hooks.onRenderProcessGone(
  165. { id: 12, getType: () => "window" },
  166. { reason: "crashed", exitCode: 139 },
  167. );
  168. const reports = sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_crash");
  169. expect(reports).toHaveLength(2);
  170. expect(reports[0]?.[0]).toMatchObject({
  171. value: 1,
  172. properties: expect.objectContaining({
  173. telemetry_schema_version: "2",
  174. crash_kind: "native",
  175. crash_scope: "main_window_renderer",
  176. crash_cause: "process_crashed",
  177. crash_source: "electron_callback",
  178. web_contents_id: "11",
  179. metric_value: "1",
  180. }),
  181. });
  182. expect(reports[0]?.[0].properties.crash_id).toMatch(
  183. /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
  184. );
  185. expect(reports[1]?.[0].properties).toMatchObject({
  186. crash_scope: "auxiliary_window_renderer",
  187. scene_window: "process_monitor",
  188. });
  189. });
  190. it("logs controlled process exits as info instead of console error", async () => {
  191. const { configureDesktopStabilityTelemetry, registerDesktopStabilityMonitors } =
  192. await import("../src/main/desktopStabilityTelemetry.js");
  193. configureDesktopStabilityTelemetry({
  194. deviceMid: "test-device",
  195. platform: "darwin",
  196. appVersion: "0.0.0-test",
  197. armsEnv: "local",
  198. });
  199. const logger = {
  200. info: vi.fn(),
  201. warn: vi.fn(),
  202. error: vi.fn(),
  203. debug: vi.fn(),
  204. };
  205. registerDesktopStabilityMonitors(logger, {} as never);
  206. const hooks = registerCrashEventMonitor.mock.calls[0]?.[2] as {
  207. onRenderProcessGone: (
  208. webContents: { id: number; getType: () => string },
  209. details: { reason: string; exitCode: number },
  210. ) => void;
  211. onChildProcessGone: (details: {
  212. type: string;
  213. reason: string;
  214. exitCode: number;
  215. serviceName?: string;
  216. name?: string;
  217. }) => void;
  218. };
  219. hooks.onRenderProcessGone(
  220. { id: 21, getType: () => "window" },
  221. { reason: "clean-exit", exitCode: 0 },
  222. );
  223. hooks.onChildProcessGone({
  224. type: "Utility",
  225. reason: "killed",
  226. exitCode: 0,
  227. name: "Network Service",
  228. });
  229. expect(logger.info).toHaveBeenCalledTimes(2);
  230. expect(logger.info).toHaveBeenCalledWith(
  231. "[stability] perf_process_exit reported",
  232. expect.objectContaining({ exit_kind: "normal" }),
  233. );
  234. expect(logger.error).not.toHaveBeenCalled();
  235. hooks.onChildProcessGone({
  236. type: "Utility",
  237. reason: "crashed",
  238. exitCode: 34,
  239. name: "Network Service",
  240. });
  241. expect(logger.warn).toHaveBeenCalledWith(
  242. "[stability] perf_process_exit reported",
  243. expect.objectContaining({ exit_kind: "recoverable_child_crash" }),
  244. );
  245. expect(logger.error).not.toHaveBeenCalled();
  246. });
  247. it("uses Electron serviceName to attribute Host crashes", async () => {
  248. const { configureDesktopStabilityTelemetry, registerDesktopStabilityMonitors } =
  249. await import("../src/main/desktopStabilityTelemetry.js");
  250. configureDesktopStabilityTelemetry({
  251. deviceMid: "test-device",
  252. platform: "darwin",
  253. appVersion: "0.0.0-test",
  254. armsEnv: "local",
  255. });
  256. const logger = {
  257. info: vi.fn(),
  258. warn: vi.fn(),
  259. error: vi.fn(),
  260. debug: vi.fn(),
  261. };
  262. registerDesktopStabilityMonitors(logger, {} as never);
  263. const hooks = registerCrashEventMonitor.mock.calls[0]?.[2] as {
  264. onChildProcessGone: (details: {
  265. type: string;
  266. reason: string;
  267. exitCode: number;
  268. serviceName?: string;
  269. name?: string;
  270. }) => void;
  271. };
  272. hooks.onChildProcessGone({
  273. type: "Utility",
  274. reason: "abnormal-exit",
  275. exitCode: 1,
  276. serviceName: "zcode-host-local-1",
  277. name: "Node Utility Process",
  278. });
  279. const report = sendCustom.mock.calls.find((call) => call[0]?.name === "perf_crash")?.[0];
  280. expect(report).toMatchObject({
  281. name: "perf_crash",
  282. properties: expect.objectContaining({
  283. crash_scope: "host",
  284. process_role: "host",
  285. process_name: "zcode-host-local-1",
  286. }),
  287. });
  288. });
  289. it.each(["oom", "memory-eviction"])(
  290. "classifies Host %s exits as OOM crashes",
  291. async (reason) => {
  292. const { configureDesktopStabilityTelemetry, registerDesktopStabilityMonitors } =
  293. await import("../src/main/desktopStabilityTelemetry.js");
  294. configureDesktopStabilityTelemetry({
  295. deviceMid: "test-device",
  296. platform: "darwin",
  297. appVersion: "0.0.0-test",
  298. armsEnv: "local",
  299. });
  300. const logger = {
  301. info: vi.fn(),
  302. warn: vi.fn(),
  303. error: vi.fn(),
  304. debug: vi.fn(),
  305. };
  306. registerDesktopStabilityMonitors(logger, {} as never);
  307. const hooks = registerCrashEventMonitor.mock.calls[0]?.[2] as {
  308. onChildProcessGone: (details: {
  309. type: string;
  310. reason: string;
  311. exitCode: number;
  312. serviceName?: string;
  313. name?: string;
  314. }) => void;
  315. };
  316. hooks.onChildProcessGone({
  317. type: "Utility",
  318. reason,
  319. exitCode: 137,
  320. serviceName: "zcode-host-local-1",
  321. name: "Node Utility Process",
  322. });
  323. const report = sendCustom.mock.calls.find((call) => call[0]?.name === "perf_crash")?.[0];
  324. expect(report).toMatchObject({
  325. name: "perf_crash",
  326. properties: expect.objectContaining({
  327. crash_kind: "oom",
  328. crash_cause: "oom",
  329. crash_scope: "host",
  330. process_role: "host",
  331. }),
  332. });
  333. },
  334. );
  335. describe("child process crash reporting", () => {
  336. it("does not report recoverable Chromium GPU and utility process exits as crash", async () => {
  337. const { shouldReportChildProcessGoneAsCrash } =
  338. await import("../src/main/desktopStabilityTelemetry.js");
  339. expect(
  340. shouldReportChildProcessGoneAsCrash({
  341. type: "GPU",
  342. reason: "crashed",
  343. exitCode: 34,
  344. name: "",
  345. }),
  346. ).toBe(false);
  347. expect(
  348. shouldReportChildProcessGoneAsCrash({
  349. type: "Utility",
  350. reason: "crashed",
  351. exitCode: -1073741205,
  352. name: "Video Capture",
  353. }),
  354. ).toBe(false);
  355. expect(
  356. shouldReportChildProcessGoneAsCrash({
  357. type: "Utility",
  358. reason: "crashed",
  359. exitCode: -1073741205,
  360. name: "Network Service",
  361. }),
  362. ).toBe(false);
  363. });
  364. it("reports zcode host child process exits as crash", async () => {
  365. const { mapChildProcessGoneToProcessRole, shouldReportChildProcessGoneAsCrash } =
  366. await import("../src/main/desktopStabilityTelemetry.js");
  367. expect(mapChildProcessGoneToProcessRole("Utility", "zcode-host-local-1")).toBe("host");
  368. expect(
  369. shouldReportChildProcessGoneAsCrash({
  370. type: "Utility",
  371. reason: "abnormal-exit",
  372. exitCode: 256,
  373. name: "zcode-host-local-1",
  374. }),
  375. ).toBe(true);
  376. });
  377. it("does not report clean child exits as crash", async () => {
  378. const { shouldReportChildProcessGoneAsCrash } =
  379. await import("../src/main/desktopStabilityTelemetry.js");
  380. expect(
  381. shouldReportChildProcessGoneAsCrash({
  382. type: "Utility",
  383. reason: "clean-exit",
  384. exitCode: 0,
  385. name: "zcode-host-local-1",
  386. }),
  387. ).toBe(false);
  388. });
  389. });
  390. describe("shouldReportAnr", () => {
  391. it("does not report below 5s threshold", async () => {
  392. const { shouldReportAnr, STABILITY_ANR_THRESHOLD_MS } =
  393. await import("../src/main/desktopStabilityTelemetry.js");
  394. expect(shouldReportAnr(STABILITY_ANR_THRESHOLD_MS - 100, false)).toBe(false);
  395. expect(shouldReportAnr(4_900, false)).toBe(false);
  396. });
  397. it("reports at 5s and only once", async () => {
  398. const { shouldReportAnr, STABILITY_ANR_THRESHOLD_MS } =
  399. await import("../src/main/desktopStabilityTelemetry.js");
  400. expect(shouldReportAnr(STABILITY_ANR_THRESHOLD_MS, false)).toBe(true);
  401. expect(shouldReportAnr(STABILITY_ANR_THRESHOLD_MS, true)).toBe(false);
  402. });
  403. });
  404. describe("shouldReportFreeze", () => {
  405. it("does not report freeze below 30s", async () => {
  406. const { shouldReportFreeze } = await import("../src/main/desktopStabilityTelemetry.js");
  407. expect(shouldReportFreeze(29_900, false, false)).toBe(false);
  408. });
  409. it("reports freeze at 30s when no crash", async () => {
  410. const { shouldReportFreeze, STABILITY_FREEZE_THRESHOLD_MS } =
  411. await import("../src/main/desktopStabilityTelemetry.js");
  412. expect(shouldReportFreeze(STABILITY_FREEZE_THRESHOLD_MS, false, false)).toBe(true);
  413. });
  414. it("does not report freeze after crash", async () => {
  415. const { shouldReportFreeze, STABILITY_FREEZE_THRESHOLD_MS } =
  416. await import("../src/main/desktopStabilityTelemetry.js");
  417. expect(shouldReportFreeze(STABILITY_FREEZE_THRESHOLD_MS, false, true)).toBe(false);
  418. });
  419. });
  420. it("attributes ANR to an auxiliary BrowserWindow instead of main", async () => {
  421. vi.useFakeTimers();
  422. try {
  423. const {
  424. configureDesktopStabilityTelemetry,
  425. registerDesktopStabilityMonitors,
  426. STABILITY_ANR_THRESHOLD_MS,
  427. } = await import("../src/main/desktopStabilityTelemetry.js");
  428. configureDesktopStabilityTelemetry({
  429. deviceMid: "test-device",
  430. platform: "darwin",
  431. appVersion: "0.0.0-test",
  432. armsEnv: "local",
  433. });
  434. const logger = {
  435. info: vi.fn(),
  436. warn: vi.fn(),
  437. error: vi.fn(),
  438. debug: vi.fn(),
  439. };
  440. const webContentsHandlers = new Map<string, () => void>();
  441. const webContents = {
  442. id: 401,
  443. getURL: () => "file:///about.html",
  444. on: vi.fn((event: string, handler: () => void) => {
  445. webContentsHandlers.set(event, handler);
  446. }),
  447. };
  448. const auxiliaryWindow = {
  449. id: 402,
  450. isDestroyed: () => false,
  451. webContents,
  452. };
  453. registerDesktopStabilityMonitors(logger, {} as never);
  454. const hooks = registerCrashEventMonitor.mock.calls[0]?.[2] as {
  455. onBrowserWindowCreated: (win: typeof auxiliaryWindow) => void;
  456. };
  457. hooks.onBrowserWindowCreated(auxiliaryWindow);
  458. webContentsHandlers.get("unresponsive")?.();
  459. vi.advanceTimersByTime(STABILITY_ANR_THRESHOLD_MS);
  460. const report = sendCustom.mock.calls.find((call) => call[0]?.name === "perf_anr")?.[0];
  461. expect(report).toMatchObject({
  462. name: "perf_anr",
  463. properties: expect.objectContaining({
  464. scene_window: "other",
  465. window_id: "402",
  466. web_contents_id: "401",
  467. }),
  468. });
  469. } finally {
  470. vi.useRealTimers();
  471. }
  472. });
  473. describe("Agent process ARMS reporting", () => {
  474. it("reports every unexpected Agent exit with count and sanitized error detail", async () => {
  475. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  476. await import("../src/main/desktopStabilityTelemetry.js");
  477. configureDesktopStabilityTelemetry({
  478. deviceMid: "test-device",
  479. platform: "darwin",
  480. appVersion: "0.0.0-test",
  481. armsEnv: "local",
  482. });
  483. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  484. const workspacePath = "/Users/alice/private-project";
  485. const event = {
  486. type: "agent-process-exited" as const,
  487. pid: 12345,
  488. provider: "glm" as const,
  489. workspacePath,
  490. runtimeInstanceId: "runtime-test-1",
  491. exitCode: 1,
  492. signal: null,
  493. endedAt: 200,
  494. terminationKind: "unexpected" as const,
  495. runtimeReady: true,
  496. runtimeGeneration: 3,
  497. uptimeMs: 100,
  498. stderrLineCount: 7,
  499. stderrTail: [
  500. `Error: write EPIPE token=super-secret at ${workspacePath}`,
  501. "request URL contains sk-1234567890abcdefghijklmnopqrstuv",
  502. ` at Socket._write (${workspacePath}/child.js:10:20)`,
  503. " at open (/Users/bob/.zcode/state.db:30:40)",
  504. " at load (/opt/zcode-private/tool.js:50:60)",
  505. " code: 'EPIPE',",
  506. "x".repeat(1_000),
  507. "x".repeat(1_000),
  508. "x".repeat(1_000),
  509. "x".repeat(1_000),
  510. ],
  511. };
  512. reportAgentProcessExitToArms(event, logger);
  513. reportAgentProcessExitToArms({ ...event, pid: 12346 }, logger);
  514. const reports = sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_agent_crash");
  515. expect(reports).toHaveLength(2);
  516. expect(reports[0][0]).toMatchObject({
  517. name: "perf_agent_crash",
  518. type: "custom",
  519. group: "stability",
  520. value: 1,
  521. properties: expect.objectContaining({
  522. process_role: "agent",
  523. incident_kind: "unexpected_exit",
  524. exit_code: "1",
  525. error_name: "Error",
  526. error_code: "EPIPE",
  527. error_message: "write EPIPE token=<redacted> at <workspace>",
  528. runtime_instance_id: "runtime-test-1",
  529. runtime_generation: "3",
  530. stderr_line_count: "7",
  531. crash_phase: "runtime",
  532. termination_class: "exit_nonzero",
  533. diagnostic_class: "errno",
  534. }),
  535. });
  536. const properties = reports[0][0].properties as Record<string, string>;
  537. expect(properties.error_stack).toContain("<workspace>");
  538. expect(properties.error_stack).not.toContain(workspacePath);
  539. expect(properties.error_stack).not.toContain("/Users/bob");
  540. expect(properties.error_stack).not.toContain("/opt/zcode-private");
  541. expect(properties.error_stack).toContain("<home>/.zcode/state.db");
  542. expect(properties.error_stack).toContain("<path>");
  543. expect(properties.error_stack).not.toContain("super-secret");
  544. expect(properties.error_stack).not.toContain("sk-1234567890abcdefghijklmnopqrstuv");
  545. expect(properties.error_stack).toContain("sk-<redacted>");
  546. expect(properties.error_stack).toHaveLength(4_000);
  547. expect(properties.error_fingerprint).toMatch(/^[0-9a-f]{16}$/);
  548. });
  549. it.each([
  550. {
  551. name: "OOM",
  552. runtimeReady: false,
  553. stderrTail: [
  554. "<--- Last few GCs --->",
  555. "[189964:0x18a8001c8000] Mark-Compact 3691 MB",
  556. "FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory",
  557. "----- Native stack trace -----",
  558. " 1: 0x00007ff6deadbeef",
  559. ],
  560. expected: {
  561. crash_phase: "startup",
  562. diagnostic_class: "oom",
  563. error_name: "AgentOutOfMemory",
  564. error_code: "ERR_OUT_OF_MEMORY",
  565. error_message: "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory",
  566. },
  567. },
  568. {
  569. name: "SQLite",
  570. runtimeReady: true,
  571. stderrTail: [
  572. "Error: SQLite migration initialization failed for C:\\Users\\alice\\.zcode\\cli\\db\\db.sqlite",
  573. ],
  574. expected: {
  575. crash_phase: "runtime",
  576. diagnostic_class: "sqlite",
  577. error_name: "Error",
  578. error_code: "",
  579. error_message:
  580. "SQLite migration initialization failed for <home>/.zcode/cli/db/db.sqlite",
  581. },
  582. },
  583. {
  584. name: "errno",
  585. runtimeReady: false,
  586. stderrTail: [
  587. "[Object]",
  588. "node:events:486",
  589. "EPERM: process.cwd failed with error operation not permitted, uv_cwd",
  590. "1: 0x00007ff6deadbeef",
  591. ],
  592. expected: {
  593. crash_phase: "startup",
  594. diagnostic_class: "errno",
  595. error_name: "AgentProcessExit",
  596. error_code: "EPERM",
  597. error_message: "EPERM: process.cwd failed with error operation not permitted, uv_cwd",
  598. },
  599. },
  600. {
  601. name: "noise only",
  602. runtimeReady: false,
  603. stderrTail: [
  604. "[Object], [Object], [Object],",
  605. "<--- Last few GCs --->",
  606. "----- Native stack trace -----",
  607. "1: 0x00007ff6deadbeef",
  608. "(node:1234) ExperimentalWarning: SQLite is an experimental feature and might change at any time",
  609. "(Use `ZCode --trace-warnings ...` to show where the warning was created)",
  610. "},",
  611. ],
  612. expected: {
  613. crash_phase: "startup",
  614. diagnostic_class: "none",
  615. error_name: "AgentProcessExit",
  616. error_code: "",
  617. error_message: "Agent process exited unexpectedly (code=1, signal=null)",
  618. },
  619. },
  620. ])(
  621. "extracts a stable $name diagnostic summary",
  622. async ({ runtimeReady, stderrTail, expected }) => {
  623. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  624. await import("../src/main/desktopStabilityTelemetry.js");
  625. configureDesktopStabilityTelemetry({
  626. deviceMid: "test-device",
  627. platform: "win32",
  628. appVersion: "0.0.0-test",
  629. armsEnv: "local",
  630. });
  631. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  632. reportAgentProcessExitToArms(
  633. {
  634. type: "agent-process-exited",
  635. pid: 12345,
  636. provider: "glm",
  637. workspacePath: "C:\\repo",
  638. runtimeInstanceId: `runtime-${expected.diagnostic_class}`,
  639. exitCode: 1,
  640. signal: null,
  641. endedAt: 200,
  642. terminationKind: "unexpected",
  643. runtimeReady,
  644. runtimeGeneration: 1,
  645. uptimeMs: 100,
  646. stderrLineCount: stderrTail.length,
  647. stderrTail,
  648. },
  649. logger,
  650. );
  651. const properties = sendCustom.mock.calls.find(
  652. (call) => call[0]?.name === "perf_agent_crash",
  653. )?.[0].properties;
  654. expect(properties).toMatchObject({
  655. ...expected,
  656. termination_class: "exit_nonzero",
  657. });
  658. expect(properties.error_message).not.toMatch(/^\[Object\]|^\d+:\s*0x|^<---|^-----/);
  659. },
  660. );
  661. it.each(["app_quit", "update_install"] as const)(
  662. "keeps %s lifecycle active and suppresses late Agent exits",
  663. async (scene) => {
  664. const {
  665. configureDesktopStabilityTelemetry,
  666. getStabilityLifecycleScene,
  667. notifyStabilityAppExit,
  668. reportAgentProcessExitToArms,
  669. } = await import("../src/main/desktopStabilityTelemetry.js");
  670. configureDesktopStabilityTelemetry({
  671. deviceMid: "test-device",
  672. platform: "win32",
  673. appVersion: "0.0.0-test",
  674. armsEnv: "local",
  675. });
  676. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
  677. notifyStabilityAppExit(scene, logger, { exitCode: 0, exitKind: "normal" });
  678. sendCustom.mockClear();
  679. reportAgentProcessExitToArms(
  680. {
  681. type: "agent-process-exited",
  682. pid: 12345,
  683. provider: "glm",
  684. workspacePath: "C:\\repo",
  685. runtimeInstanceId: "runtime-shutdown",
  686. exitCode: 1073807364,
  687. signal: null,
  688. endedAt: 200,
  689. terminationKind: "unexpected",
  690. runtimeGeneration: 1,
  691. uptimeMs: 100,
  692. stderrLineCount: 0,
  693. },
  694. logger,
  695. );
  696. expect(getStabilityLifecycleScene()).toBe(scene);
  697. expect(
  698. sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_agent_crash"),
  699. ).toHaveLength(0);
  700. },
  701. );
  702. it.each([
  703. {
  704. name: "Windows 0x40010004",
  705. platform: "win32" as const,
  706. exitCode: 0x40010004,
  707. signal: null,
  708. },
  709. {
  710. name: "POSIX SIGTERM",
  711. platform: "linux" as const,
  712. exitCode: null,
  713. signal: "SIGTERM",
  714. },
  715. ])("does not report controlled termination signature: $name", async (input) => {
  716. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  717. await import("../src/main/desktopStabilityTelemetry.js");
  718. configureDesktopStabilityTelemetry({
  719. deviceMid: "test-device",
  720. platform: input.platform,
  721. appVersion: "0.0.0-test",
  722. armsEnv: "local",
  723. });
  724. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
  725. reportAgentProcessExitToArms(
  726. {
  727. type: "agent-process-exited",
  728. pid: 12345,
  729. provider: "glm",
  730. workspacePath: input.platform === "win32" ? "C:\\repo" : "/repo",
  731. runtimeInstanceId: "runtime-controlled-termination",
  732. exitCode: input.exitCode,
  733. signal: input.signal,
  734. endedAt: 200,
  735. terminationKind: "unexpected",
  736. runtimeGeneration: 1,
  737. uptimeMs: 100,
  738. stderrLineCount: 0,
  739. },
  740. logger,
  741. );
  742. expect(
  743. sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_agent_crash"),
  744. ).toHaveLength(0);
  745. });
  746. it.each([
  747. {
  748. name: "Windows 0x40010004",
  749. platform: "win32" as const,
  750. workspacePath: "C:\\repo",
  751. exitCode: 0x40010004,
  752. signal: null,
  753. terminationClass: "exit_nonzero",
  754. },
  755. {
  756. name: "POSIX SIGTERM",
  757. platform: "linux" as const,
  758. workspacePath: "/repo",
  759. exitCode: null,
  760. signal: "SIGTERM",
  761. terminationClass: "signal",
  762. },
  763. ])("reports protocol failure after controlled cleanup: $name", async (input) => {
  764. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  765. await import("../src/main/desktopStabilityTelemetry.js");
  766. configureDesktopStabilityTelemetry({
  767. deviceMid: "test-device",
  768. platform: input.platform,
  769. appVersion: "0.0.0-test",
  770. armsEnv: "local",
  771. });
  772. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
  773. reportAgentProcessExitToArms(
  774. {
  775. type: "agent-process-exited",
  776. pid: 12345,
  777. provider: "glm",
  778. workspacePath: input.workspacePath,
  779. runtimeInstanceId: "runtime-protocol-failure",
  780. exitCode: input.exitCode,
  781. signal: input.signal,
  782. endedAt: 200,
  783. terminationKind: "unexpected",
  784. terminationReason: "protocol-close",
  785. runtimeGeneration: 1,
  786. uptimeMs: 100,
  787. stderrLineCount: 0,
  788. },
  789. logger,
  790. );
  791. const reports = sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_agent_crash");
  792. expect(reports).toHaveLength(1);
  793. expect(reports[0]?.[0].properties).toMatchObject({
  794. termination_class: input.terminationClass,
  795. termination_reason: "protocol-close",
  796. });
  797. });
  798. it("still reports an unexpected SIGKILL during runtime", async () => {
  799. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  800. await import("../src/main/desktopStabilityTelemetry.js");
  801. configureDesktopStabilityTelemetry({
  802. deviceMid: "test-device",
  803. platform: "linux",
  804. appVersion: "0.0.0-test",
  805. armsEnv: "local",
  806. });
  807. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
  808. reportAgentProcessExitToArms(
  809. {
  810. type: "agent-process-exited",
  811. pid: 12345,
  812. provider: "glm",
  813. workspacePath: "/repo",
  814. runtimeInstanceId: "runtime-sigkill",
  815. exitCode: null,
  816. signal: "SIGKILL",
  817. endedAt: 200,
  818. terminationKind: "unexpected",
  819. runtimeGeneration: 1,
  820. uptimeMs: 100,
  821. stderrLineCount: 0,
  822. },
  823. logger,
  824. );
  825. const reports = sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_agent_crash");
  826. expect(reports).toHaveLength(1);
  827. expect(reports[0]?.[0].properties).toMatchObject({
  828. crash_phase: "unknown",
  829. termination_class: "signal",
  830. });
  831. });
  832. it("classifies an unexpected clean code as exit_zero crash", async () => {
  833. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  834. await import("../src/main/desktopStabilityTelemetry.js");
  835. configureDesktopStabilityTelemetry({
  836. deviceMid: "test-device",
  837. platform: "linux",
  838. appVersion: "0.0.0-test",
  839. armsEnv: "local",
  840. });
  841. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  842. reportAgentProcessExitToArms(
  843. {
  844. type: "agent-process-exited",
  845. pid: 12345,
  846. provider: "glm",
  847. workspacePath: "/repo",
  848. runtimeInstanceId: "runtime-exit-zero",
  849. exitCode: 0,
  850. signal: null,
  851. endedAt: 200,
  852. terminationKind: "unexpected",
  853. runtimeReady: true,
  854. runtimeGeneration: 1,
  855. uptimeMs: 100,
  856. stderrLineCount: 0,
  857. },
  858. logger,
  859. );
  860. expect(
  861. sendCustom.mock.calls.find((call) => call[0]?.name === "perf_agent_crash")?.[0].properties,
  862. ).toMatchObject({
  863. crash_phase: "runtime",
  864. termination_class: "exit_zero",
  865. });
  866. });
  867. it("does not report expected or watchdog Agent exits", async () => {
  868. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  869. await import("../src/main/desktopStabilityTelemetry.js");
  870. configureDesktopStabilityTelemetry({
  871. deviceMid: "test-device",
  872. platform: "win32",
  873. appVersion: "0.0.0-test",
  874. armsEnv: "local",
  875. });
  876. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  877. const base = {
  878. type: "agent-process-exited" as const,
  879. pid: 12345,
  880. provider: "glm" as const,
  881. workspacePath: "C:\\repo",
  882. runtimeInstanceId: "runtime-test-2",
  883. exitCode: 1,
  884. signal: null,
  885. endedAt: 200,
  886. runtimeGeneration: 1,
  887. uptimeMs: 100,
  888. stderrLineCount: 0,
  889. };
  890. reportAgentProcessExitToArms(
  891. {
  892. ...base,
  893. terminationKind: "expected",
  894. terminationReason: "workspace-dispose",
  895. },
  896. logger,
  897. );
  898. reportAgentProcessExitToArms(
  899. {
  900. ...base,
  901. terminationKind: "watchdog_recycle",
  902. terminationReason: "request-timeout",
  903. },
  904. logger,
  905. );
  906. expect(
  907. sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_agent_crash"),
  908. ).toHaveLength(0);
  909. });
  910. it("normalizes home paths and uses the meaningful errno line for Agent fingerprints", async () => {
  911. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  912. await import("../src/main/desktopStabilityTelemetry.js");
  913. configureDesktopStabilityTelemetry({
  914. deviceMid: "test-device",
  915. platform: "darwin",
  916. appVersion: "0.0.0-test",
  917. armsEnv: "local",
  918. });
  919. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  920. const base = {
  921. type: "agent-process-exited" as const,
  922. pid: 12345,
  923. provider: "glm" as const,
  924. workspacePath: "/repo",
  925. exitCode: 1,
  926. signal: null,
  927. endedAt: 200,
  928. terminationKind: "unexpected" as const,
  929. runtimeGeneration: 1,
  930. uptimeMs: 100,
  931. stderrLineCount: 3,
  932. };
  933. reportAgentProcessExitToArms(
  934. {
  935. ...base,
  936. runtimeInstanceId: "runtime-path-a",
  937. stderrTail: [
  938. "[Object]",
  939. "node:events:486",
  940. "EPERM: process.cwd failed at /Users/alice/.zcode/state.db:10:20",
  941. ],
  942. },
  943. logger,
  944. );
  945. reportAgentProcessExitToArms(
  946. {
  947. ...base,
  948. runtimeInstanceId: "runtime-path-b",
  949. stderrTail: [
  950. "[Object]",
  951. "node:events:999",
  952. "EPERM: process.cwd failed at /home/bob/.zcode/state.db:30:40",
  953. ],
  954. },
  955. logger,
  956. );
  957. const reports = sendCustom.mock.calls
  958. .filter((call) => call[0]?.name === "perf_agent_crash")
  959. .map((call) => call[0].properties as Record<string, string>);
  960. expect(reports.map((report) => report.error_message)).toEqual([
  961. "EPERM: process.cwd failed at <home>/.zcode/state.db:10:20",
  962. "EPERM: process.cwd failed at <home>/.zcode/state.db:30:40",
  963. ]);
  964. expect(reports.map((report) => report.error_code)).toEqual(["EPERM", "EPERM"]);
  965. expect(reports[0]?.error_fingerprint).toBe(reports[1]?.error_fingerprint);
  966. });
  967. it("reports Agent spawn errors without command or workspace paths", async () => {
  968. const { configureDesktopStabilityTelemetry, reportAgentProcessSpawnErrorToArms } =
  969. await import("../src/main/desktopStabilityTelemetry.js");
  970. configureDesktopStabilityTelemetry({
  971. deviceMid: "test-device",
  972. platform: "linux",
  973. appVersion: "0.0.0-test",
  974. armsEnv: "local",
  975. });
  976. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  977. const workspacePath = "/home/alice/private-project";
  978. reportAgentProcessSpawnErrorToArms(
  979. {
  980. type: "agent-process-error",
  981. pid: null,
  982. provider: "glm",
  983. workspacePath,
  984. runtimeInstanceId: "runtime-test-3",
  985. command: `${workspacePath}/missing-agent`,
  986. args: ["app-server", "--stdio", "--token=must-not-upload"],
  987. errorName: "Error",
  988. errorCode: "ENOENT",
  989. errorMessage: `spawn ${workspacePath}/missing-agent ENOENT sk-abcdefghijklmnopqrstuv0123456789`,
  990. errorStack: `Error: spawn ${workspacePath}/missing-agent ENOENT sk-abcdefghijklmnopqrstuv0123456789`,
  991. runtimeGeneration: 1,
  992. occurredAt: 100,
  993. },
  994. logger,
  995. );
  996. const report = sendCustom.mock.calls.find(
  997. (call) => call[0]?.name === "perf_agent_spawn_error",
  998. )?.[0];
  999. expect(report).toMatchObject({
  1000. name: "perf_agent_spawn_error",
  1001. type: "custom",
  1002. group: "stability",
  1003. value: 1,
  1004. properties: expect.objectContaining({
  1005. process_role: "agent",
  1006. incident_kind: "spawn_error",
  1007. error_code: "ENOENT",
  1008. error_message: "spawn <workspace>/missing-agent ENOENT sk-<redacted>",
  1009. diagnostic_class: "errno",
  1010. runtime_instance_id: "runtime-test-3",
  1011. }),
  1012. });
  1013. expect(JSON.stringify(report)).not.toContain(workspacePath);
  1014. expect(JSON.stringify(report)).not.toContain("must-not-upload");
  1015. expect(JSON.stringify(report)).not.toContain("sk-abcdefghijklmnopqrstuv0123456789");
  1016. expect(JSON.stringify(report)).toContain("sk-<redacted>");
  1017. });
  1018. it("reports one Agent start with the runtime instance used by its later crash", async () => {
  1019. const { configureDesktopStabilityTelemetry, reportAgentProcessStartToArms } =
  1020. await import("../src/main/desktopStabilityTelemetry.js");
  1021. configureDesktopStabilityTelemetry({
  1022. deviceMid: "test-device",
  1023. platform: "linux",
  1024. appVersion: "0.0.0-test",
  1025. armsEnv: "local",
  1026. });
  1027. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  1028. reportAgentProcessStartToArms(
  1029. {
  1030. type: "agent-process-spawned",
  1031. pid: 12345,
  1032. provider: "glm",
  1033. workspacePath: "/repo/demo",
  1034. command: "/tmp/zcode-agent",
  1035. args: ["app-server", "--stdio"],
  1036. startedAt: 100,
  1037. runtimeGeneration: 4,
  1038. runtimeInstanceId: "runtime-test-4",
  1039. },
  1040. logger,
  1041. );
  1042. expect(
  1043. sendCustom.mock.calls.find((call) => call[0]?.name === "perf_agent_start")?.[0],
  1044. ).toMatchObject({
  1045. name: "perf_agent_start",
  1046. value: 1,
  1047. properties: expect.objectContaining({
  1048. process_role: "agent",
  1049. runtime_generation: "4",
  1050. runtime_instance_id: "runtime-test-4",
  1051. }),
  1052. });
  1053. });
  1054. it("reports Agent ready with the same runtime instance and startup duration", async () => {
  1055. const { configureDesktopStabilityTelemetry, reportAgentProcessReadyToArms } =
  1056. await import("../src/main/desktopStabilityTelemetry.js");
  1057. configureDesktopStabilityTelemetry({
  1058. deviceMid: "test-device",
  1059. platform: "linux",
  1060. appVersion: "0.0.0-test",
  1061. armsEnv: "local",
  1062. });
  1063. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  1064. reportAgentProcessReadyToArms(
  1065. {
  1066. type: "agent-process-ready",
  1067. pid: 12345,
  1068. provider: "glm",
  1069. workspacePath: "/repo/demo",
  1070. readyAt: 250,
  1071. startupDurationMs: 150,
  1072. runtimeGeneration: 4,
  1073. runtimeInstanceId: "runtime-test-4",
  1074. },
  1075. logger,
  1076. );
  1077. expect(
  1078. sendCustom.mock.calls.find((call) => call[0]?.name === "perf_agent_ready")?.[0],
  1079. ).toMatchObject({
  1080. name: "perf_agent_ready",
  1081. value: 1,
  1082. properties: expect.objectContaining({
  1083. process_role: "agent",
  1084. runtime_generation: "4",
  1085. runtime_instance_id: "runtime-test-4",
  1086. startup_duration_ms: "150",
  1087. }),
  1088. });
  1089. });
  1090. });
  1091. describe("reportPerfAppStart", () => {
  1092. it("sends perf_app_start only once per process", async () => {
  1093. const { configureDesktopStabilityTelemetry, reportPerfAppStart } =
  1094. await import("../src/main/desktopStabilityTelemetry.js");
  1095. configureDesktopStabilityTelemetry({
  1096. deviceMid: "test-device",
  1097. platform: "darwin",
  1098. appVersion: "0.0.0-test",
  1099. armsEnv: "local",
  1100. });
  1101. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  1102. reportPerfAppStart(logger);
  1103. reportPerfAppStart(logger);
  1104. const perfStarts = sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_app_start");
  1105. expect(perfStarts).toHaveLength(1);
  1106. expect(perfStarts[0][0]).toMatchObject({
  1107. name: "perf_app_start",
  1108. type: "custom",
  1109. group: "stability",
  1110. value: 1,
  1111. });
  1112. expect(perfStarts[0][0].properties).toMatchObject({
  1113. event_name: "perf_app_start",
  1114. scene_lifecycle: "cold_start",
  1115. scene_window: "main",
  1116. device_mid: "test-device",
  1117. telemetry_schema_version: "2",
  1118. });
  1119. });
  1120. });
  1121. });