desktopStabilityTelemetry.test.ts 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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"])("classifies Host %s exits as OOM crashes", async (reason) => {
  290. const { configureDesktopStabilityTelemetry, registerDesktopStabilityMonitors } =
  291. await import("../src/main/desktopStabilityTelemetry.js");
  292. configureDesktopStabilityTelemetry({
  293. deviceMid: "test-device",
  294. platform: "darwin",
  295. appVersion: "0.0.0-test",
  296. armsEnv: "local",
  297. });
  298. const logger = {
  299. info: vi.fn(),
  300. warn: vi.fn(),
  301. error: vi.fn(),
  302. debug: vi.fn(),
  303. };
  304. registerDesktopStabilityMonitors(logger, {} as never);
  305. const hooks = registerCrashEventMonitor.mock.calls[0]?.[2] as {
  306. onChildProcessGone: (details: {
  307. type: string;
  308. reason: string;
  309. exitCode: number;
  310. serviceName?: string;
  311. name?: string;
  312. }) => void;
  313. };
  314. hooks.onChildProcessGone({
  315. type: "Utility",
  316. reason,
  317. exitCode: 137,
  318. serviceName: "zcode-host-local-1",
  319. name: "Node Utility Process",
  320. });
  321. const report = sendCustom.mock.calls.find((call) => call[0]?.name === "perf_crash")?.[0];
  322. expect(report).toMatchObject({
  323. name: "perf_crash",
  324. properties: expect.objectContaining({
  325. crash_kind: "oom",
  326. crash_cause: "oom",
  327. crash_scope: "host",
  328. process_role: "host",
  329. }),
  330. });
  331. });
  332. describe("child process crash reporting", () => {
  333. it("does not report recoverable Chromium GPU and utility process exits as crash", async () => {
  334. const { shouldReportChildProcessGoneAsCrash } =
  335. await import("../src/main/desktopStabilityTelemetry.js");
  336. expect(
  337. shouldReportChildProcessGoneAsCrash({
  338. type: "GPU",
  339. reason: "crashed",
  340. exitCode: 34,
  341. name: "",
  342. }),
  343. ).toBe(false);
  344. expect(
  345. shouldReportChildProcessGoneAsCrash({
  346. type: "Utility",
  347. reason: "crashed",
  348. exitCode: -1073741205,
  349. name: "Video Capture",
  350. }),
  351. ).toBe(false);
  352. expect(
  353. shouldReportChildProcessGoneAsCrash({
  354. type: "Utility",
  355. reason: "crashed",
  356. exitCode: -1073741205,
  357. name: "Network Service",
  358. }),
  359. ).toBe(false);
  360. });
  361. it("reports zcode host child process exits as crash", async () => {
  362. const { mapChildProcessGoneToProcessRole, shouldReportChildProcessGoneAsCrash } =
  363. await import("../src/main/desktopStabilityTelemetry.js");
  364. expect(mapChildProcessGoneToProcessRole("Utility", "zcode-host-local-1")).toBe("host");
  365. expect(
  366. shouldReportChildProcessGoneAsCrash({
  367. type: "Utility",
  368. reason: "abnormal-exit",
  369. exitCode: 256,
  370. name: "zcode-host-local-1",
  371. }),
  372. ).toBe(true);
  373. });
  374. it("does not report clean child exits as crash", async () => {
  375. const { shouldReportChildProcessGoneAsCrash } =
  376. await import("../src/main/desktopStabilityTelemetry.js");
  377. expect(
  378. shouldReportChildProcessGoneAsCrash({
  379. type: "Utility",
  380. reason: "clean-exit",
  381. exitCode: 0,
  382. name: "zcode-host-local-1",
  383. }),
  384. ).toBe(false);
  385. });
  386. });
  387. describe("shouldReportAnr", () => {
  388. it("does not report below 5s threshold", async () => {
  389. const { shouldReportAnr } = await import("../src/main/desktopStabilityTelemetry.js");
  390. expect(shouldReportAnr(4_900, false)).toBe(false);
  391. });
  392. it("reports at 5s and only once", async () => {
  393. const { shouldReportAnr, STABILITY_ANR_THRESHOLD_MS } =
  394. await import("../src/main/desktopStabilityTelemetry.js");
  395. expect(shouldReportAnr(STABILITY_ANR_THRESHOLD_MS, false)).toBe(true);
  396. expect(shouldReportAnr(STABILITY_ANR_THRESHOLD_MS, true)).toBe(false);
  397. });
  398. });
  399. describe("shouldReportFreeze", () => {
  400. it("does not report freeze below 30s", async () => {
  401. const { shouldReportFreeze } = await import("../src/main/desktopStabilityTelemetry.js");
  402. expect(shouldReportFreeze(29_900, false, false)).toBe(false);
  403. });
  404. it("reports freeze at 30s when no crash", async () => {
  405. const { shouldReportFreeze, STABILITY_FREEZE_THRESHOLD_MS } =
  406. await import("../src/main/desktopStabilityTelemetry.js");
  407. expect(shouldReportFreeze(STABILITY_FREEZE_THRESHOLD_MS, false, false)).toBe(true);
  408. });
  409. it("does not report freeze after crash", async () => {
  410. const { shouldReportFreeze, STABILITY_FREEZE_THRESHOLD_MS } =
  411. await import("../src/main/desktopStabilityTelemetry.js");
  412. expect(shouldReportFreeze(STABILITY_FREEZE_THRESHOLD_MS, false, true)).toBe(false);
  413. });
  414. });
  415. it("attributes ANR to an auxiliary BrowserWindow instead of main", async () => {
  416. vi.useFakeTimers();
  417. try {
  418. const {
  419. configureDesktopStabilityTelemetry,
  420. registerDesktopStabilityMonitors,
  421. STABILITY_ANR_THRESHOLD_MS,
  422. } = await import("../src/main/desktopStabilityTelemetry.js");
  423. configureDesktopStabilityTelemetry({
  424. deviceMid: "test-device",
  425. platform: "darwin",
  426. appVersion: "0.0.0-test",
  427. armsEnv: "local",
  428. });
  429. const logger = {
  430. info: vi.fn(),
  431. warn: vi.fn(),
  432. error: vi.fn(),
  433. debug: vi.fn(),
  434. };
  435. const webContentsHandlers = new Map<string, () => void>();
  436. const webContents = {
  437. id: 401,
  438. getURL: () => "file:///about.html",
  439. on: vi.fn((event: string, handler: () => void) => {
  440. webContentsHandlers.set(event, handler);
  441. }),
  442. };
  443. const auxiliaryWindow = {
  444. id: 402,
  445. isDestroyed: () => false,
  446. webContents,
  447. };
  448. registerDesktopStabilityMonitors(logger, {} as never);
  449. const hooks = registerCrashEventMonitor.mock.calls[0]?.[2] as {
  450. onBrowserWindowCreated: (win: typeof auxiliaryWindow) => void;
  451. };
  452. hooks.onBrowserWindowCreated(auxiliaryWindow);
  453. webContentsHandlers.get("unresponsive")?.();
  454. vi.advanceTimersByTime(STABILITY_ANR_THRESHOLD_MS);
  455. const report = sendCustom.mock.calls.find((call) => call[0]?.name === "perf_anr")?.[0];
  456. expect(report).toMatchObject({
  457. name: "perf_anr",
  458. properties: expect.objectContaining({
  459. scene_window: "other",
  460. window_id: "402",
  461. web_contents_id: "401",
  462. }),
  463. });
  464. } finally {
  465. vi.useRealTimers();
  466. }
  467. });
  468. describe("Agent process ARMS reporting", () => {
  469. it("reports every unexpected Agent exit with count and sanitized error detail", async () => {
  470. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  471. await import("../src/main/desktopStabilityTelemetry.js");
  472. configureDesktopStabilityTelemetry({
  473. deviceMid: "test-device",
  474. platform: "darwin",
  475. appVersion: "0.0.0-test",
  476. armsEnv: "local",
  477. });
  478. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  479. const workspacePath = "/Users/alice/private-project";
  480. const event = {
  481. type: "agent-process-exited" as const,
  482. pid: 12345,
  483. provider: "glm" as const,
  484. workspacePath,
  485. runtimeInstanceId: "runtime-test-1",
  486. exitCode: 1,
  487. signal: null,
  488. endedAt: 200,
  489. terminationKind: "unexpected" as const,
  490. runtimeReady: true,
  491. runtimeGeneration: 3,
  492. uptimeMs: 100,
  493. stderrLineCount: 7,
  494. stderrTail: [
  495. `Error: write EPIPE token=super-secret at ${workspacePath}`,
  496. "request URL contains sk-1234567890abcdefghijklmnopqrstuv",
  497. ` at Socket._write (${workspacePath}/child.js:10:20)`,
  498. " at open (/Users/bob/.zcode/state.db:30:40)",
  499. " at load (/opt/zcode-private/tool.js:50:60)",
  500. " code: 'EPIPE',",
  501. "x".repeat(1_000),
  502. "x".repeat(1_000),
  503. "x".repeat(1_000),
  504. "x".repeat(1_000),
  505. ],
  506. };
  507. reportAgentProcessExitToArms(event, logger);
  508. reportAgentProcessExitToArms({ ...event, pid: 12346 }, logger);
  509. const reports = sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_agent_crash");
  510. expect(reports).toHaveLength(2);
  511. expect(reports[0][0]).toMatchObject({
  512. name: "perf_agent_crash",
  513. type: "custom",
  514. group: "stability",
  515. value: 1,
  516. properties: expect.objectContaining({
  517. process_role: "agent",
  518. incident_kind: "unexpected_exit",
  519. exit_code: "1",
  520. error_name: "Error",
  521. error_code: "EPIPE",
  522. error_message: "write EPIPE token=<redacted> at <workspace>",
  523. runtime_instance_id: "runtime-test-1",
  524. runtime_generation: "3",
  525. stderr_line_count: "7",
  526. crash_phase: "runtime",
  527. termination_class: "exit_nonzero",
  528. diagnostic_class: "errno",
  529. }),
  530. });
  531. const properties = reports[0][0].properties as Record<string, string>;
  532. expect(properties.error_stack).toContain("<workspace>");
  533. expect(properties.error_stack).not.toContain(workspacePath);
  534. expect(properties.error_stack).not.toContain("/Users/bob");
  535. expect(properties.error_stack).not.toContain("/opt/zcode-private");
  536. expect(properties.error_stack).toContain("<home>/.zcode/state.db");
  537. expect(properties.error_stack).toContain("<path>");
  538. expect(properties.error_stack).not.toContain("super-secret");
  539. expect(properties.error_stack).not.toContain("sk-1234567890abcdefghijklmnopqrstuv");
  540. expect(properties.error_stack).toContain("sk-<redacted>");
  541. expect(properties.error_stack).toHaveLength(4_000);
  542. expect(properties.error_fingerprint).toMatch(/^[0-9a-f]{16}$/);
  543. });
  544. it.each([
  545. {
  546. name: "OOM",
  547. runtimeReady: false,
  548. stderrTail: [
  549. "<--- Last few GCs --->",
  550. "[189964:0x18a8001c8000] Mark-Compact 3691 MB",
  551. "FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory",
  552. "----- Native stack trace -----",
  553. " 1: 0x00007ff6deadbeef",
  554. ],
  555. expected: {
  556. crash_phase: "startup",
  557. diagnostic_class: "oom",
  558. error_name: "AgentOutOfMemory",
  559. error_code: "ERR_OUT_OF_MEMORY",
  560. error_message: "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory",
  561. },
  562. },
  563. {
  564. name: "SQLite",
  565. runtimeReady: true,
  566. stderrTail: [
  567. "Error: SQLite migration initialization failed for C:\\Users\\alice\\.zcode\\cli\\db\\db.sqlite",
  568. ],
  569. expected: {
  570. crash_phase: "runtime",
  571. diagnostic_class: "sqlite",
  572. error_name: "Error",
  573. error_code: "",
  574. error_message:
  575. "SQLite migration initialization failed for <home>/.zcode/cli/db/db.sqlite",
  576. },
  577. },
  578. {
  579. name: "errno",
  580. runtimeReady: false,
  581. stderrTail: [
  582. "[Object]",
  583. "node:events:486",
  584. "EPERM: process.cwd failed with error operation not permitted, uv_cwd",
  585. "1: 0x00007ff6deadbeef",
  586. ],
  587. expected: {
  588. crash_phase: "startup",
  589. diagnostic_class: "errno",
  590. error_name: "AgentProcessExit",
  591. error_code: "EPERM",
  592. error_message: "EPERM: process.cwd failed with error operation not permitted, uv_cwd",
  593. },
  594. },
  595. {
  596. name: "noise only",
  597. runtimeReady: false,
  598. stderrTail: [
  599. "[Object], [Object], [Object],",
  600. "<--- Last few GCs --->",
  601. "----- Native stack trace -----",
  602. "1: 0x00007ff6deadbeef",
  603. "(node:1234) ExperimentalWarning: SQLite is an experimental feature and might change at any time",
  604. "(Use `ZCode --trace-warnings ...` to show where the warning was created)",
  605. "},",
  606. ],
  607. expected: {
  608. crash_phase: "startup",
  609. diagnostic_class: "none",
  610. error_name: "AgentProcessExit",
  611. error_code: "",
  612. error_message: "Agent process exited unexpectedly (code=1, signal=null)",
  613. },
  614. },
  615. ])(
  616. "extracts a stable $name diagnostic summary",
  617. async ({ runtimeReady, stderrTail, expected }) => {
  618. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  619. await import("../src/main/desktopStabilityTelemetry.js");
  620. configureDesktopStabilityTelemetry({
  621. deviceMid: "test-device",
  622. platform: "win32",
  623. appVersion: "0.0.0-test",
  624. armsEnv: "local",
  625. });
  626. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  627. reportAgentProcessExitToArms(
  628. {
  629. type: "agent-process-exited",
  630. pid: 12345,
  631. provider: "glm",
  632. workspacePath: "C:\\repo",
  633. runtimeInstanceId: `runtime-${expected.diagnostic_class}`,
  634. exitCode: 1,
  635. signal: null,
  636. endedAt: 200,
  637. terminationKind: "unexpected",
  638. runtimeReady,
  639. runtimeGeneration: 1,
  640. uptimeMs: 100,
  641. stderrLineCount: stderrTail.length,
  642. stderrTail,
  643. },
  644. logger,
  645. );
  646. const properties = sendCustom.mock.calls.find(
  647. (call) => call[0]?.name === "perf_agent_crash",
  648. )?.[0].properties;
  649. expect(properties).toMatchObject({
  650. ...expected,
  651. termination_class: "exit_nonzero",
  652. });
  653. expect(properties.error_message).not.toMatch(/^\[Object\]|^\d+:\s*0x|^<---|^-----/);
  654. },
  655. );
  656. it.each(["app_quit", "update_install"] as const)(
  657. "keeps %s lifecycle active and suppresses late Agent exits",
  658. async (scene) => {
  659. const {
  660. configureDesktopStabilityTelemetry,
  661. getStabilityLifecycleScene,
  662. notifyStabilityAppExit,
  663. reportAgentProcessExitToArms,
  664. } = await import("../src/main/desktopStabilityTelemetry.js");
  665. configureDesktopStabilityTelemetry({
  666. deviceMid: "test-device",
  667. platform: "win32",
  668. appVersion: "0.0.0-test",
  669. armsEnv: "local",
  670. });
  671. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
  672. notifyStabilityAppExit(scene, logger, { exitCode: 0, exitKind: "normal" });
  673. sendCustom.mockClear();
  674. reportAgentProcessExitToArms(
  675. {
  676. type: "agent-process-exited",
  677. pid: 12345,
  678. provider: "glm",
  679. workspacePath: "C:\\repo",
  680. runtimeInstanceId: "runtime-shutdown",
  681. exitCode: 1073807364,
  682. signal: null,
  683. endedAt: 200,
  684. terminationKind: "unexpected",
  685. runtimeGeneration: 1,
  686. uptimeMs: 100,
  687. stderrLineCount: 0,
  688. },
  689. logger,
  690. );
  691. expect(getStabilityLifecycleScene()).toBe(scene);
  692. expect(
  693. sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_agent_crash"),
  694. ).toHaveLength(0);
  695. },
  696. );
  697. it.each([
  698. {
  699. name: "Windows 0x40010004",
  700. platform: "win32" as const,
  701. exitCode: 0x40010004,
  702. signal: null,
  703. },
  704. {
  705. name: "POSIX SIGTERM",
  706. platform: "linux" as const,
  707. exitCode: null,
  708. signal: "SIGTERM",
  709. },
  710. ])("does not report controlled termination signature: $name", async (input) => {
  711. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  712. await import("../src/main/desktopStabilityTelemetry.js");
  713. configureDesktopStabilityTelemetry({
  714. deviceMid: "test-device",
  715. platform: input.platform,
  716. appVersion: "0.0.0-test",
  717. armsEnv: "local",
  718. });
  719. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
  720. reportAgentProcessExitToArms(
  721. {
  722. type: "agent-process-exited",
  723. pid: 12345,
  724. provider: "glm",
  725. workspacePath: input.platform === "win32" ? "C:\\repo" : "/repo",
  726. runtimeInstanceId: "runtime-controlled-termination",
  727. exitCode: input.exitCode,
  728. signal: input.signal,
  729. endedAt: 200,
  730. terminationKind: "unexpected",
  731. runtimeGeneration: 1,
  732. uptimeMs: 100,
  733. stderrLineCount: 0,
  734. },
  735. logger,
  736. );
  737. expect(
  738. sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_agent_crash"),
  739. ).toHaveLength(0);
  740. });
  741. it.each([
  742. {
  743. name: "Windows 0x40010004",
  744. platform: "win32" as const,
  745. workspacePath: "C:\\repo",
  746. exitCode: 0x40010004,
  747. signal: null,
  748. terminationClass: "exit_nonzero",
  749. },
  750. {
  751. name: "POSIX SIGTERM",
  752. platform: "linux" as const,
  753. workspacePath: "/repo",
  754. exitCode: null,
  755. signal: "SIGTERM",
  756. terminationClass: "signal",
  757. },
  758. ])("reports protocol failure after controlled cleanup: $name", async (input) => {
  759. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  760. await import("../src/main/desktopStabilityTelemetry.js");
  761. configureDesktopStabilityTelemetry({
  762. deviceMid: "test-device",
  763. platform: input.platform,
  764. appVersion: "0.0.0-test",
  765. armsEnv: "local",
  766. });
  767. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
  768. reportAgentProcessExitToArms(
  769. {
  770. type: "agent-process-exited",
  771. pid: 12345,
  772. provider: "glm",
  773. workspacePath: input.workspacePath,
  774. runtimeInstanceId: "runtime-protocol-failure",
  775. exitCode: input.exitCode,
  776. signal: input.signal,
  777. endedAt: 200,
  778. terminationKind: "unexpected",
  779. terminationReason: "protocol-close",
  780. runtimeGeneration: 1,
  781. uptimeMs: 100,
  782. stderrLineCount: 0,
  783. },
  784. logger,
  785. );
  786. const reports = sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_agent_crash");
  787. expect(reports).toHaveLength(1);
  788. expect(reports[0]?.[0].properties).toMatchObject({
  789. termination_class: input.terminationClass,
  790. termination_reason: "protocol-close",
  791. });
  792. });
  793. it("still reports an unexpected SIGKILL during runtime", async () => {
  794. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  795. await import("../src/main/desktopStabilityTelemetry.js");
  796. configureDesktopStabilityTelemetry({
  797. deviceMid: "test-device",
  798. platform: "linux",
  799. appVersion: "0.0.0-test",
  800. armsEnv: "local",
  801. });
  802. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
  803. reportAgentProcessExitToArms(
  804. {
  805. type: "agent-process-exited",
  806. pid: 12345,
  807. provider: "glm",
  808. workspacePath: "/repo",
  809. runtimeInstanceId: "runtime-sigkill",
  810. exitCode: null,
  811. signal: "SIGKILL",
  812. endedAt: 200,
  813. terminationKind: "unexpected",
  814. runtimeGeneration: 1,
  815. uptimeMs: 100,
  816. stderrLineCount: 0,
  817. },
  818. logger,
  819. );
  820. const reports = sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_agent_crash");
  821. expect(reports).toHaveLength(1);
  822. expect(reports[0]?.[0].properties).toMatchObject({
  823. crash_phase: "unknown",
  824. termination_class: "signal",
  825. });
  826. });
  827. it("classifies an unexpected clean code as exit_zero crash", async () => {
  828. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  829. await import("../src/main/desktopStabilityTelemetry.js");
  830. configureDesktopStabilityTelemetry({
  831. deviceMid: "test-device",
  832. platform: "linux",
  833. appVersion: "0.0.0-test",
  834. armsEnv: "local",
  835. });
  836. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  837. reportAgentProcessExitToArms(
  838. {
  839. type: "agent-process-exited",
  840. pid: 12345,
  841. provider: "glm",
  842. workspacePath: "/repo",
  843. runtimeInstanceId: "runtime-exit-zero",
  844. exitCode: 0,
  845. signal: null,
  846. endedAt: 200,
  847. terminationKind: "unexpected",
  848. runtimeReady: true,
  849. runtimeGeneration: 1,
  850. uptimeMs: 100,
  851. stderrLineCount: 0,
  852. },
  853. logger,
  854. );
  855. expect(
  856. sendCustom.mock.calls.find((call) => call[0]?.name === "perf_agent_crash")?.[0].properties,
  857. ).toMatchObject({
  858. crash_phase: "runtime",
  859. termination_class: "exit_zero",
  860. });
  861. });
  862. it("does not report expected or watchdog Agent exits", async () => {
  863. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  864. await import("../src/main/desktopStabilityTelemetry.js");
  865. configureDesktopStabilityTelemetry({
  866. deviceMid: "test-device",
  867. platform: "win32",
  868. appVersion: "0.0.0-test",
  869. armsEnv: "local",
  870. });
  871. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  872. const base = {
  873. type: "agent-process-exited" as const,
  874. pid: 12345,
  875. provider: "glm" as const,
  876. workspacePath: "C:\\repo",
  877. runtimeInstanceId: "runtime-test-2",
  878. exitCode: 1,
  879. signal: null,
  880. endedAt: 200,
  881. runtimeGeneration: 1,
  882. uptimeMs: 100,
  883. stderrLineCount: 0,
  884. };
  885. reportAgentProcessExitToArms(
  886. {
  887. ...base,
  888. terminationKind: "expected",
  889. terminationReason: "workspace-dispose",
  890. },
  891. logger,
  892. );
  893. reportAgentProcessExitToArms(
  894. {
  895. ...base,
  896. terminationKind: "watchdog_recycle",
  897. terminationReason: "request-timeout",
  898. },
  899. logger,
  900. );
  901. expect(
  902. sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_agent_crash"),
  903. ).toHaveLength(0);
  904. });
  905. it("normalizes home paths and uses the meaningful errno line for Agent fingerprints", async () => {
  906. const { configureDesktopStabilityTelemetry, reportAgentProcessExitToArms } =
  907. await import("../src/main/desktopStabilityTelemetry.js");
  908. configureDesktopStabilityTelemetry({
  909. deviceMid: "test-device",
  910. platform: "darwin",
  911. appVersion: "0.0.0-test",
  912. armsEnv: "local",
  913. });
  914. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  915. const base = {
  916. type: "agent-process-exited" as const,
  917. pid: 12345,
  918. provider: "glm" as const,
  919. workspacePath: "/repo",
  920. exitCode: 1,
  921. signal: null,
  922. endedAt: 200,
  923. terminationKind: "unexpected" as const,
  924. runtimeGeneration: 1,
  925. uptimeMs: 100,
  926. stderrLineCount: 3,
  927. };
  928. reportAgentProcessExitToArms(
  929. {
  930. ...base,
  931. runtimeInstanceId: "runtime-path-a",
  932. stderrTail: [
  933. "[Object]",
  934. "node:events:486",
  935. "EPERM: process.cwd failed at /Users/alice/.zcode/state.db:10:20",
  936. ],
  937. },
  938. logger,
  939. );
  940. reportAgentProcessExitToArms(
  941. {
  942. ...base,
  943. runtimeInstanceId: "runtime-path-b",
  944. stderrTail: [
  945. "[Object]",
  946. "node:events:999",
  947. "EPERM: process.cwd failed at /home/bob/.zcode/state.db:30:40",
  948. ],
  949. },
  950. logger,
  951. );
  952. const reports = sendCustom.mock.calls
  953. .filter((call) => call[0]?.name === "perf_agent_crash")
  954. .map((call) => call[0].properties as Record<string, string>);
  955. expect(reports.map((report) => report.error_message)).toEqual([
  956. "EPERM: process.cwd failed at <home>/.zcode/state.db:10:20",
  957. "EPERM: process.cwd failed at <home>/.zcode/state.db:30:40",
  958. ]);
  959. expect(reports.map((report) => report.error_code)).toEqual(["EPERM", "EPERM"]);
  960. expect(reports[0]?.error_fingerprint).toBe(reports[1]?.error_fingerprint);
  961. });
  962. it("reports Agent spawn errors without command or workspace paths", async () => {
  963. const { configureDesktopStabilityTelemetry, reportAgentProcessSpawnErrorToArms } =
  964. await import("../src/main/desktopStabilityTelemetry.js");
  965. configureDesktopStabilityTelemetry({
  966. deviceMid: "test-device",
  967. platform: "linux",
  968. appVersion: "0.0.0-test",
  969. armsEnv: "local",
  970. });
  971. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  972. const workspacePath = "/home/alice/private-project";
  973. reportAgentProcessSpawnErrorToArms(
  974. {
  975. type: "agent-process-error",
  976. pid: null,
  977. provider: "glm",
  978. workspacePath,
  979. runtimeInstanceId: "runtime-test-3",
  980. command: `${workspacePath}/missing-agent`,
  981. args: ["app-server", "--stdio", "--token=must-not-upload"],
  982. errorName: "Error",
  983. errorCode: "ENOENT",
  984. errorMessage: `spawn ${workspacePath}/missing-agent ENOENT sk-abcdefghijklmnopqrstuv0123456789`,
  985. errorStack: `Error: spawn ${workspacePath}/missing-agent ENOENT sk-abcdefghijklmnopqrstuv0123456789`,
  986. runtimeGeneration: 1,
  987. occurredAt: 100,
  988. },
  989. logger,
  990. );
  991. const report = sendCustom.mock.calls.find(
  992. (call) => call[0]?.name === "perf_agent_spawn_error",
  993. )?.[0];
  994. expect(report).toMatchObject({
  995. name: "perf_agent_spawn_error",
  996. type: "custom",
  997. group: "stability",
  998. value: 1,
  999. properties: expect.objectContaining({
  1000. process_role: "agent",
  1001. incident_kind: "spawn_error",
  1002. error_code: "ENOENT",
  1003. error_message: "spawn <workspace>/missing-agent ENOENT sk-<redacted>",
  1004. diagnostic_class: "errno",
  1005. runtime_instance_id: "runtime-test-3",
  1006. }),
  1007. });
  1008. expect(JSON.stringify(report)).not.toContain(workspacePath);
  1009. expect(JSON.stringify(report)).not.toContain("must-not-upload");
  1010. expect(JSON.stringify(report)).not.toContain("sk-abcdefghijklmnopqrstuv0123456789");
  1011. expect(JSON.stringify(report)).toContain("sk-<redacted>");
  1012. });
  1013. it("reports one Agent start with the runtime instance used by its later crash", async () => {
  1014. const { configureDesktopStabilityTelemetry, reportAgentProcessStartToArms } =
  1015. await import("../src/main/desktopStabilityTelemetry.js");
  1016. configureDesktopStabilityTelemetry({
  1017. deviceMid: "test-device",
  1018. platform: "linux",
  1019. appVersion: "0.0.0-test",
  1020. armsEnv: "local",
  1021. });
  1022. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  1023. reportAgentProcessStartToArms(
  1024. {
  1025. type: "agent-process-spawned",
  1026. pid: 12345,
  1027. provider: "glm",
  1028. workspacePath: "/repo/demo",
  1029. command: "/tmp/zcode-agent",
  1030. args: ["app-server", "--stdio"],
  1031. startedAt: 100,
  1032. runtimeGeneration: 4,
  1033. runtimeInstanceId: "runtime-test-4",
  1034. },
  1035. logger,
  1036. );
  1037. expect(
  1038. sendCustom.mock.calls.find((call) => call[0]?.name === "perf_agent_start")?.[0],
  1039. ).toMatchObject({
  1040. name: "perf_agent_start",
  1041. value: 1,
  1042. properties: expect.objectContaining({
  1043. process_role: "agent",
  1044. runtime_generation: "4",
  1045. runtime_instance_id: "runtime-test-4",
  1046. }),
  1047. });
  1048. });
  1049. it("reports Agent ready with the same runtime instance and startup duration", async () => {
  1050. const { configureDesktopStabilityTelemetry, reportAgentProcessReadyToArms } =
  1051. await import("../src/main/desktopStabilityTelemetry.js");
  1052. configureDesktopStabilityTelemetry({
  1053. deviceMid: "test-device",
  1054. platform: "linux",
  1055. appVersion: "0.0.0-test",
  1056. armsEnv: "local",
  1057. });
  1058. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  1059. reportAgentProcessReadyToArms(
  1060. {
  1061. type: "agent-process-ready",
  1062. pid: 12345,
  1063. provider: "glm",
  1064. workspacePath: "/repo/demo",
  1065. readyAt: 250,
  1066. startupDurationMs: 150,
  1067. runtimeGeneration: 4,
  1068. runtimeInstanceId: "runtime-test-4",
  1069. },
  1070. logger,
  1071. );
  1072. expect(
  1073. sendCustom.mock.calls.find((call) => call[0]?.name === "perf_agent_ready")?.[0],
  1074. ).toMatchObject({
  1075. name: "perf_agent_ready",
  1076. value: 1,
  1077. properties: expect.objectContaining({
  1078. process_role: "agent",
  1079. runtime_generation: "4",
  1080. runtime_instance_id: "runtime-test-4",
  1081. startup_duration_ms: "150",
  1082. }),
  1083. });
  1084. });
  1085. });
  1086. describe("reportPerfAppStart", () => {
  1087. it("sends perf_app_start only once per process", async () => {
  1088. const { configureDesktopStabilityTelemetry, reportPerfAppStart } =
  1089. await import("../src/main/desktopStabilityTelemetry.js");
  1090. configureDesktopStabilityTelemetry({
  1091. deviceMid: "test-device",
  1092. platform: "darwin",
  1093. appVersion: "0.0.0-test",
  1094. armsEnv: "local",
  1095. });
  1096. const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
  1097. reportPerfAppStart(logger);
  1098. reportPerfAppStart(logger);
  1099. const perfStarts = sendCustom.mock.calls.filter((call) => call[0]?.name === "perf_app_start");
  1100. expect(perfStarts).toHaveLength(1);
  1101. expect(perfStarts[0][0]).toMatchObject({
  1102. name: "perf_app_start",
  1103. type: "custom",
  1104. group: "stability",
  1105. value: 1,
  1106. });
  1107. expect(perfStarts[0][0].properties).toMatchObject({
  1108. event_name: "perf_app_start",
  1109. scene_lifecycle: "cold_start",
  1110. scene_window: "main",
  1111. device_mid: "test-device",
  1112. telemetry_schema_version: "2",
  1113. });
  1114. });
  1115. });
  1116. });