appARMSBootstrap.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. import { readFile } from "node:fs/promises";
  2. import { fileURLToPath } from "node:url";
  3. import { runInNewContext } from "node:vm";
  4. import { beforeEach, describe, expect, it, vi } from "vitest";
  5. import { ZCODE_AGENT_LIFECYCLE_LOG_MARKER } from "@zcode/shared/process-diagnostic";
  6. const init = vi.fn((_config: unknown) => Promise.resolve());
  7. vi.mock("@arms/rum-electron", () => ({
  8. default: { init, client: { useReporter: vi.fn() } },
  9. }));
  10. vi.mock("../src/main/desktopDeviceMid.js", () => ({
  11. ensureDesktopDeviceMidSync: vi.fn(() => "test-device-mid"),
  12. }));
  13. vi.mock("../src/main/desktopNetworkTelemetry.js", () => ({
  14. ingestArmsApiEventsFromBatch: vi.fn(),
  15. }));
  16. vi.mock("../src/main/desktopRuntimeEnv.js", () => ({
  17. desktopRuntimeEnv: "development",
  18. runtimeApplicationName: "zcode-test",
  19. }));
  20. vi.mock("../src/main/logger.js", () => ({
  21. logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
  22. }));
  23. vi.mock("@zcode/shared", async (importOriginal) => {
  24. // 脱敏收口是 beforeReport 的一部分,必须用真实实现验证;只覆写环境/版本等常量。
  25. const actual = await importOriginal<typeof import("@zcode/shared")>();
  26. return {
  27. ...actual,
  28. ZCODE_ARMS_RUM_ENDPOINT: "https://example.test/endpoint",
  29. ZCODE_ENV: "test",
  30. ZCODE_VERSION: "0.0.0-test",
  31. mapZCodeEnvToArmsRumEnv: vi.fn(() => "local"),
  32. };
  33. });
  34. // beforeReport 是 armsRum.init(config) 里的一个字段;直接从 mock 的 init 调用参数里取出来调用,
  35. // 不需要走真实上报网络请求,即可验证 LoAF 归因摘要被正确合并进 event.properties。
  36. async function getBeforeReport(): Promise<
  37. (payload: { events?: Array<Record<string, unknown>> }) => unknown
  38. > {
  39. await import("../src/main/appARMSBootstrap.js");
  40. const config = init.mock.calls[0]?.[0] as unknown as {
  41. beforeReport: (payload: { events?: Array<Record<string, unknown>> }) => unknown;
  42. };
  43. return config.beforeReport;
  44. }
  45. async function getPatchedReadCrashProcessType(): Promise<
  46. (input: Uint8Array) => string | undefined
  47. > {
  48. const packageEntry = fileURLToPath(
  49. new URL("../../../node_modules/@arms/rum-electron/dist/index.mjs", import.meta.url),
  50. );
  51. const source = await readFile(packageEntry, "utf8");
  52. const parserStart = source.indexOf("const zcodeCrashpadInfoStreamType");
  53. const parserEnd = source.indexOf("\nclass ", parserStart);
  54. expect(parserStart).toBeGreaterThanOrEqual(0);
  55. expect(parserEnd).toBeGreaterThan(parserStart);
  56. return runInNewContext(`${source.slice(parserStart, parserEnd)}; readCrashProcessType`, {
  57. Buffer,
  58. }) as (input: Uint8Array) => string | undefined;
  59. }
  60. async function getPatchedFormatConsoleErrorArgs(): Promise<(args: unknown[]) => string> {
  61. const packageEntry = fileURLToPath(
  62. new URL("../../../node_modules/@arms/rum-electron/dist/index.mjs", import.meta.url),
  63. );
  64. const source = await readFile(packageEntry, "utf8");
  65. const formatterStart = source.indexOf("const zcodeConsoleErrorMaxLength");
  66. const formatterEnd = source.indexOf("\nclass ", formatterStart);
  67. expect(formatterStart).toBeGreaterThanOrEqual(0);
  68. expect(formatterEnd).toBeGreaterThan(formatterStart);
  69. return runInNewContext(
  70. `${source.slice(formatterStart, formatterEnd)}; zcodeFormatConsoleErrorArgs`,
  71. ) as (args: unknown[]) => string;
  72. }
  73. function alignToFour(value: number): number {
  74. return (value + 3) & ~3;
  75. }
  76. function buildCrashpadProcessTypeDump(options: {
  77. annotationKey: "process_type" | "ptype";
  78. processType: string;
  79. decoyProcessType?: string;
  80. }): Uint8Array {
  81. const dump = Buffer.alloc(512);
  82. const directoryRva = 32;
  83. const crashpadInfoRva = 128;
  84. const moduleListRva = 192;
  85. const moduleInfoRva = 208;
  86. const annotationListRva = 236;
  87. const annotationNameRva = 252;
  88. const annotationValueRva = alignToFour(
  89. annotationNameRva + 4 + Buffer.byteLength(options.annotationKey) + 1,
  90. );
  91. dump.write("MDMP", 0, "ascii");
  92. dump.writeUInt32LE(1, 8);
  93. dump.writeUInt32LE(directoryRva, 12);
  94. dump.writeUInt32LE(0x43500001, directoryRva);
  95. dump.writeUInt32LE(64, directoryRva + 4);
  96. dump.writeUInt32LE(crashpadInfoRva, directoryRva + 8);
  97. if (options.decoyProcessType) {
  98. const decoyRva = 48;
  99. dump.writeUInt32LE(12, decoyRva);
  100. dump.write("process_type", decoyRva + 4, "utf8");
  101. const decoyValueLengthRva = decoyRva + 4 + 12 + 4;
  102. dump.writeUInt32LE(Buffer.byteLength(options.decoyProcessType), decoyValueLengthRva);
  103. dump.write(options.decoyProcessType, decoyValueLengthRva + 4, "utf8");
  104. }
  105. dump.writeUInt32LE(1, crashpadInfoRva);
  106. dump.writeUInt32LE(16, crashpadInfoRva + 44);
  107. dump.writeUInt32LE(moduleListRva, crashpadInfoRva + 48);
  108. dump.writeUInt32LE(1, moduleListRva);
  109. dump.writeUInt32LE(0, moduleListRva + 4);
  110. dump.writeUInt32LE(28, moduleListRva + 8);
  111. dump.writeUInt32LE(moduleInfoRva, moduleListRva + 12);
  112. dump.writeUInt32LE(1, moduleInfoRva);
  113. dump.writeUInt32LE(16, moduleInfoRva + 20);
  114. dump.writeUInt32LE(annotationListRva, moduleInfoRva + 24);
  115. dump.writeUInt32LE(1, annotationListRva);
  116. dump.writeUInt32LE(annotationNameRva, annotationListRva + 4);
  117. dump.writeUInt16LE(1, annotationListRva + 8);
  118. dump.writeUInt16LE(0, annotationListRva + 10);
  119. dump.writeUInt32LE(annotationValueRva, annotationListRva + 12);
  120. dump.writeUInt32LE(Buffer.byteLength(options.annotationKey), annotationNameRva);
  121. dump.write(options.annotationKey, annotationNameRva + 4, "utf8");
  122. dump.writeUInt32LE(Buffer.byteLength(options.processType), annotationValueRva);
  123. dump.write(options.processType, annotationValueRva + 4, "utf8");
  124. return dump;
  125. }
  126. describe("appARMSBootstrap beforeReport", () => {
  127. it("filters only explicitly marked lifecycle console wrappers, preserving real JS errors", async () => {
  128. const beforeReport = await getBeforeReport();
  129. const wrapper = {
  130. event_type: "exception",
  131. type: "error",
  132. source: "console.error",
  133. message: `[host-log] process exited ${ZCODE_AGENT_LIFECYCLE_LOG_MARKER}`,
  134. };
  135. const realError = { ...wrapper, source: "uncaughtException" };
  136. const normalConsoleError = { ...wrapper, message: "a real main error" };
  137. const custom = { event_type: "custom", name: "perf_agent_crash" };
  138. expect(
  139. beforeReport({ events: [wrapper, realError, normalConsoleError, custom] }),
  140. ).toMatchObject({
  141. events: [realError, normalConsoleError, custom],
  142. });
  143. });
  144. it("在返回 payload 前脱敏自动采集事件的界面文本、路径与 URL", async () => {
  145. const beforeReport = await getBeforeReport();
  146. const result = beforeReport({
  147. events: [
  148. {
  149. event_type: "click",
  150. name: "click on button: 重构 src/auth 登录流程...",
  151. snapshots: JSON.stringify({ src: "file:///Users/alice/p/a.png" }),
  152. },
  153. {
  154. event_type: "exception",
  155. type: "error",
  156. source: "uncaughtException",
  157. message: "ENOENT '/Users/alice/work/secret/a.ts' for bob@example.com",
  158. },
  159. {
  160. event_type: "resource",
  161. type: "api",
  162. url: "https://zcode.z.ai/api/v1/event/report?state=abc123",
  163. },
  164. ],
  165. }) as { events: Array<Record<string, unknown>> };
  166. expect(result.events[0]!.name).toBe("click on button");
  167. expect(result.events[0]!.snapshots).toBeUndefined();
  168. expect(result.events[1]!.message).not.toContain("alice");
  169. expect(result.events[1]!.message).not.toContain("secret");
  170. expect(result.events[1]!.message).not.toContain("bob@example.com");
  171. expect(result.events[2]!.url).toBe("https://zcode.z.ai/api/v1/event/report");
  172. });
  173. it("脱敏排在网络 ingest 之后,聚合仍拿到原始 URL", async () => {
  174. const { ingestArmsApiEventsFromBatch } = await import("../src/main/desktopNetworkTelemetry.js");
  175. // 脱敏是就地改写,mock 记录的是同一个对象引用;必须在 ingest 被调用的那一刻取快照,
  176. // 否则读到的是脱敏后的值,无法证明聚合看到的是原始 URL。
  177. const urlsSeenByAggregator: unknown[] = [];
  178. vi.mocked(ingestArmsApiEventsFromBatch).mockImplementation((events) => {
  179. for (const event of events ?? []) {
  180. urlsSeenByAggregator.push(event.url);
  181. }
  182. });
  183. const beforeReport = await getBeforeReport();
  184. const events = [
  185. {
  186. event_type: "resource",
  187. type: "api",
  188. url: "https://zcode.z.ai/api/v1/tasks/0f8fad5b-d9cb-469f-a165-70867728950e?token=x",
  189. },
  190. ];
  191. beforeReport({ events });
  192. expect(urlsSeenByAggregator).toEqual([
  193. "https://zcode.z.ai/api/v1/tasks/0f8fad5b-d9cb-469f-a165-70867728950e?token=x",
  194. ]);
  195. expect(events[0]!.url).toBe("https://zcode.z.ai/api/v1/tasks/{segment}");
  196. });
  197. beforeEach(() => {
  198. vi.resetModules();
  199. init.mockClear();
  200. });
  201. it("使用 Desktop 本地开发运行态计算 ARMS 环境", async () => {
  202. await import("../src/main/appARMSBootstrap.js");
  203. const shared = await import("@zcode/shared");
  204. const config = init.mock.calls[0]?.[0] as unknown as {
  205. env: string;
  206. app: { env: string };
  207. tracing: { sample: number };
  208. };
  209. expect(shared.mapZCodeEnvToArmsRumEnv).toHaveBeenCalledWith("development");
  210. expect(config).toMatchObject({
  211. env: "local",
  212. app: { env: "local" },
  213. tracing: { sample: 1 },
  214. });
  215. });
  216. it("为 longTask 事件补写归因摘要到 properties", async () => {
  217. const beforeReport = await getBeforeReport();
  218. const snapshots = JSON.stringify([
  219. { duration: 30, invokerType: "event-listener" },
  220. { duration: 90, invokerType: "user-callback" },
  221. ]);
  222. const longTaskEvent: Record<string, unknown> = {
  223. event_type: "longTask",
  224. duration: 150,
  225. snapshots,
  226. };
  227. const result = beforeReport({ events: [longTaskEvent] }) as {
  228. events: Array<Record<string, unknown>>;
  229. };
  230. expect(result.events[0].properties).toEqual({
  231. loaf_script_count: 2,
  232. loaf_top_duration_ms: 90,
  233. loaf_top_invoker_type: "user-callback",
  234. loaf_top_share_pct: 60,
  235. });
  236. });
  237. it("不影响非 longTask 事件,不新增 properties 字段", async () => {
  238. const beforeReport = await getBeforeReport();
  239. const customEvent: Record<string, unknown> = {
  240. event_type: "custom",
  241. name: "perf_ui_first_token",
  242. properties: { model: "test-model" },
  243. };
  244. const result = beforeReport({ events: [customEvent] }) as {
  245. events: Array<Record<string, unknown>>;
  246. };
  247. expect(result.events[0].properties).toEqual({ model: "test-model" });
  248. });
  249. it("longTask 事件缺少有效 snapshots 时不新增 properties", async () => {
  250. const beforeReport = await getBeforeReport();
  251. const longTaskEvent: Record<string, unknown> = {
  252. event_type: "longTask",
  253. duration: 150,
  254. snapshots: null,
  255. };
  256. const result = beforeReport({ events: [longTaskEvent] }) as {
  257. events: Array<Record<string, unknown>>;
  258. };
  259. expect(result.events[0].properties).toBeUndefined();
  260. });
  261. it("drops crashReporter dumps that do not contain the ZCode product binary", async () => {
  262. const beforeReport = await getBeforeReport();
  263. const externalCrash = {
  264. event_type: "exception",
  265. type: "crash",
  266. source: "crashReporter",
  267. binary_images: [{ name: "hdc" }, { name: "libsystem_kernel.dylib" }],
  268. };
  269. const zcodeCrash = {
  270. event_type: "exception",
  271. type: "crash",
  272. source: "crashReporter",
  273. meta: { process_type: "browser" },
  274. binary_images: [{ name: "zcode-test" }, { name: "Electron Framework" }],
  275. };
  276. const helperCrash = {
  277. event_type: "exception",
  278. type: "crash",
  279. source: "crashReporter",
  280. binary_images: [{ name: "zcode-test Helper (Renderer)" }],
  281. };
  282. const customEvent = { event_type: "custom", name: "perf_app_start" };
  283. const result = beforeReport({
  284. events: [externalCrash, helperCrash, zcodeCrash, customEvent],
  285. }) as {
  286. events: Array<Record<string, unknown>>;
  287. };
  288. expect(result.events).toHaveLength(2);
  289. expect(result.events).not.toContain(externalCrash);
  290. expect(result.events).not.toContain(helperCrash);
  291. expect(result.events).toContain(customEvent);
  292. expect(result.events[0]).toMatchObject({
  293. source: "crashReporter",
  294. properties: {
  295. telemetry_schema_version: "2",
  296. crash_scope: "app_native_process",
  297. crash_cause: "native_crash",
  298. crash_source: "crash_reporter_dump",
  299. },
  300. });
  301. const firstCrashId = (result.events[0].properties as Record<string, unknown> | undefined)
  302. ?.crash_id;
  303. const retried = beforeReport({ events: result.events }) as {
  304. events: Array<Record<string, unknown>>;
  305. };
  306. expect((retried.events[0].properties as Record<string, unknown> | undefined)?.crash_id).toBe(
  307. firstCrashId,
  308. );
  309. });
  310. it("does not promote an unattributed product dump into app_native_process", async () => {
  311. const beforeReport = await getBeforeReport();
  312. const dump = {
  313. event_type: "exception",
  314. type: "crash",
  315. source: "crashReporter",
  316. binary_images: [{ name: "zcode-test" }],
  317. };
  318. const result = beforeReport({ events: [dump] }) as {
  319. events: Array<Record<string, unknown>>;
  320. };
  321. expect(result.events[0]).toMatchObject({
  322. properties: {
  323. telemetry_schema_version: "2",
  324. crash_scope: "native_dump_unattributed",
  325. crash_cause: "native_crash",
  326. crash_source: "crash_reporter_dump",
  327. native_dump_process_role: "unknown",
  328. },
  329. });
  330. });
  331. it("uses the SDK-preserved process_type and never infers role from meta.process", async () => {
  332. const beforeReport = await getBeforeReport();
  333. const dump = {
  334. event_type: "exception",
  335. type: "crash",
  336. source: "crashReporter",
  337. meta: { process: "zcode-test", process_type: "browser" },
  338. binary_images: [{ name: "zcode-test" }],
  339. };
  340. const result = beforeReport({ events: [dump] }) as {
  341. events: Array<Record<string, unknown>>;
  342. };
  343. expect(result.events[0]).toMatchObject({
  344. properties: {
  345. crash_scope: "app_native_process",
  346. native_dump_process_role: "main",
  347. },
  348. });
  349. });
  350. it.each([
  351. { source: "top-level process_role", eventPatch: { process_role: "main" } },
  352. {
  353. source: "top-level native_dump_process_role",
  354. eventPatch: { native_dump_process_role: "main" },
  355. },
  356. { source: "meta.process_role", eventPatch: { meta: { process_role: "main" } } },
  357. {
  358. source: "properties.process_role",
  359. eventPatch: { properties: { process_role: "main" } },
  360. },
  361. {
  362. source: "properties.native_dump_process_role",
  363. eventPatch: { properties: { native_dump_process_role: "main" } },
  364. },
  365. ] satisfies Array<{ source: string; eventPatch: Record<string, unknown> }>)(
  366. "does not trust $source as a native dump process role",
  367. async ({ eventPatch }) => {
  368. const { filterAndEnrichNativeCrashEvents } = await import("../src/main/appARMSBootstrap.js");
  369. const dump = {
  370. event_type: "exception",
  371. type: "crash",
  372. source: "crashReporter",
  373. binary_images: [{ name: "zcode-test" }],
  374. ...eventPatch,
  375. };
  376. const events = filterAndEnrichNativeCrashEvents([dump], "zcode-test", "zcode-test");
  377. expect(events[0]).toMatchObject({
  378. properties: {
  379. crash_scope: "native_dump_unattributed",
  380. native_dump_process_role: "unknown",
  381. },
  382. });
  383. },
  384. );
  385. it.each(["process_type", "ptype"] as const)(
  386. "reads the structured Crashpad %s annotation",
  387. async (annotationKey) => {
  388. const readCrashProcessType = await getPatchedReadCrashProcessType();
  389. const dump = buildCrashpadProcessTypeDump({ annotationKey, processType: "browser" });
  390. expect(readCrashProcessType(dump)).toBe("browser");
  391. },
  392. );
  393. it("ignores unreferenced process_type bytes before the structured annotation", async () => {
  394. const readCrashProcessType = await getPatchedReadCrashProcessType();
  395. const dump = buildCrashpadProcessTypeDump({
  396. annotationKey: "ptype",
  397. processType: "renderer",
  398. decoyProcessType: "browser",
  399. });
  400. expect(readCrashProcessType(dump)).toBe("renderer");
  401. });
  402. it.each(["renderer", "utility", "gpu", "host"])(
  403. "keeps a %s dump out of app_native_process even when the product binary matches",
  404. async (processRole) => {
  405. const { filterAndEnrichNativeCrashEvents } = await import("../src/main/appARMSBootstrap.js");
  406. const dump = {
  407. event_type: "exception",
  408. type: "crash",
  409. source: "crashReporter",
  410. meta: { process_type: processRole },
  411. binary_images: [{ name: "zcode-test" }],
  412. };
  413. const events = filterAndEnrichNativeCrashEvents([dump], "zcode-test", "zcode-test");
  414. expect(events[0]).toMatchObject({
  415. properties: {
  416. crash_scope: "native_dump_unattributed",
  417. native_dump_process_role: processRole,
  418. },
  419. });
  420. },
  421. );
  422. it("keeps a dump attributed to the main process in app_native_process", async () => {
  423. const { filterAndEnrichNativeCrashEvents } = await import("../src/main/appARMSBootstrap.js");
  424. const dump = {
  425. event_type: "exception",
  426. type: "crash",
  427. source: "crashReporter",
  428. meta: { process_type: "browser" },
  429. binary_images: [{ name: "zcode-test" }],
  430. };
  431. const events = filterAndEnrichNativeCrashEvents([dump], "zcode-test", "zcode-test");
  432. expect(events[0]).toMatchObject({
  433. properties: {
  434. crash_scope: "app_native_process",
  435. native_dump_process_role: "main",
  436. },
  437. });
  438. });
  439. it.each([
  440. {
  441. runtime: "Linux Preview",
  442. applicationName: "ZCode Preview",
  443. executableName: "zcode-preview",
  444. },
  445. {
  446. runtime: "local development",
  447. applicationName: "ZCode Dev",
  448. executableName: "Electron",
  449. },
  450. ])(
  451. "keeps a $runtime dump whose executable name differs from the application name",
  452. async ({ applicationName, executableName }) => {
  453. const { filterAndEnrichNativeCrashEvents } = await import("../src/main/appARMSBootstrap.js");
  454. const crash = {
  455. event_type: "exception",
  456. type: "crash",
  457. source: "crashReporter",
  458. meta: { process_type: "browser" },
  459. binary_images: [{ name: executableName }],
  460. };
  461. const events = filterAndEnrichNativeCrashEvents([crash], applicationName, executableName);
  462. expect(events).toEqual([crash]);
  463. },
  464. );
  465. });
  466. describe("patched ARMS console error formatter", () => {
  467. it.each(["main", "renderer"])(
  468. "removes the %s logger prefix and preserves every meaningful argument",
  469. async (source) => {
  470. const formatConsoleErrorArgs = await getPatchedFormatConsoleErrorArgs();
  471. expect(
  472. formatConsoleErrorArgs([
  473. `[2026-08-20 17:04:22.265] [pid:25144] [${source}]`,
  474. "[stability] perf_process_exit reported",
  475. { exitCode: 0, reason: "clean-exit" },
  476. ]),
  477. ).toBe('[stability] perf_process_exit reported {"exitCode":0,"reason":"clean-exit"}');
  478. },
  479. );
  480. it("redacts secrets, tolerates circular values, and caps the reported message", async () => {
  481. const formatConsoleErrorArgs = await getPatchedFormatConsoleErrorArgs();
  482. const circular: Record<string, unknown> = {
  483. token: "super-secret",
  484. authorization: "Bearer abcdefghijklmnopqrstuvwxyz",
  485. };
  486. circular.self = circular;
  487. const result = formatConsoleErrorArgs([
  488. "failed with sk-1234567890abcdefghijklmnopqrstuv",
  489. circular,
  490. "x".repeat(4_000),
  491. ]);
  492. expect(result).not.toContain("super-secret");
  493. expect(result).not.toContain("sk-1234567890abcdefghijklmnopqrstuv");
  494. expect(result).not.toContain("abcdefghijklmnopqrstuvwxyz");
  495. expect(result).toContain("<redacted>");
  496. expect(result).toContain("[Circular]");
  497. expect(result.length).toBeLessThanOrEqual(2_000);
  498. });
  499. it("drops a public prefix without a business message", async () => {
  500. const formatConsoleErrorArgs = await getPatchedFormatConsoleErrorArgs();
  501. expect(formatConsoleErrorArgs(["[2026-08-20 17:04:22.265] [pid:25144] [main]"])).toBe("");
  502. });
  503. });