uiPerfArmsTelemetry.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import type { ArmsCustomEventPayload } from "@zcode/shared";
  3. import {
  4. INPUT_LAG_REPORT_THRESHOLD_MS,
  5. INPUT_LAG_SANITY_MAX_MS,
  6. LAUNCH_TO_INPUT_SANITY_MAX_MS,
  7. STREAM_STALL_REPORT_THRESHOLD_MS,
  8. UI_PERF_ARMS_GROUP,
  9. UI_PERF_EVENT_INPUT_LAG,
  10. UI_PERF_EVENT_LAUNCH_ELECTRON_INIT,
  11. UI_PERF_EVENT_LAUNCH_REACT_COMMIT,
  12. UI_PERF_EVENT_LAUNCH_STARTUP_GATE,
  13. UI_PERF_EVENT_LAUNCH_TO_INPUT,
  14. UI_PERF_EVENT_TOOL_CALL_DETAIL,
  15. UI_PERF_EVENT_TURN_BREAKDOWN,
  16. clearStreamStallTracking,
  17. clearUiPerfArmsReporterForTest,
  18. recordStreamChunkArrival,
  19. recordInputLag,
  20. reportUiFirstToken,
  21. reportUiLaunchToInput,
  22. reportUiMessageComplete,
  23. reportUiToolCallDetail,
  24. reportUiTurnBreakdown,
  25. setUiPerfArmsReporter,
  26. shouldReportInputLag,
  27. } from "@/lib/uiPerfArmsTelemetry.js";
  28. function makeReporter() {
  29. const calls: ArmsCustomEventPayload[] = [];
  30. return {
  31. calls,
  32. reportArmsCustomEvent: vi.fn(async (payload: ArmsCustomEventPayload) => {
  33. calls.push(payload);
  34. }),
  35. };
  36. }
  37. function makeTimings(
  38. overrides?: Partial<{
  39. createdAt: number;
  40. mainStart: number;
  41. appReady: number;
  42. loadUrl: number;
  43. rendererStart: number;
  44. reactCommit: number;
  45. inputReady: number;
  46. }>,
  47. ) {
  48. const base = {
  49. createdAt: 1000,
  50. mainStart: 1600, // electron_init = 600
  51. appReady: 1780, // app_ready = 180
  52. loadUrl: 2020, // window = 240
  53. rendererStart: 2930, // renderer_load = 910
  54. reactCommit: 3005, // react_commit = 75
  55. inputReady: 3820, // startup_gate = 815, total = 2820
  56. ...overrides,
  57. };
  58. return {
  59. marks: {
  60. createdAt: base.createdAt,
  61. mainStart: base.mainStart,
  62. appReady: base.appReady,
  63. loadUrl: base.loadUrl,
  64. },
  65. rendererStart: base.rendererStart,
  66. reactCommit: base.reactCommit,
  67. inputReady: base.inputReady,
  68. sessionId: "sess-1",
  69. };
  70. }
  71. afterEach(() => {
  72. clearUiPerfArmsReporterForTest();
  73. vi.restoreAllMocks();
  74. });
  75. describe("uiPerfArmsTelemetry: 通用", () => {
  76. it("未注入 reporter 时静默不抛错", () => {
  77. expect(() => reportUiLaunchToInput(makeTimings())).not.toThrow();
  78. });
  79. it("reportUiFirstToken 带 model/talk_id/message_id", () => {
  80. const reporter = makeReporter();
  81. setUiPerfArmsReporter(reporter);
  82. reportUiFirstToken({
  83. ttftMs: 800,
  84. model: "glm-4.6",
  85. talkId: "t1",
  86. messageId: "m1",
  87. });
  88. expect(reporter.calls[0]).toMatchObject({
  89. name: "perf_ui_first_token",
  90. group: UI_PERF_ARMS_GROUP,
  91. value: 800,
  92. properties: { model: "glm-4.6", talk_id: "t1", message_id: "m1" },
  93. });
  94. });
  95. it("未命中白名单的模型归一为 custom,不原样透传", () => {
  96. const reporter = makeReporter();
  97. setUiPerfArmsReporter(reporter);
  98. reportUiFirstToken({ ttftMs: 800, model: "internal-preview-model", talkId: "t1" });
  99. expect(reporter.calls[0]?.properties?.model).toBe("custom");
  100. });
  101. it("自定义 provider 的编码模型值不泄露 provider 名与模型名", () => {
  102. const reporter = makeReporter();
  103. setUiPerfArmsReporter(reporter);
  104. reportUiMessageComplete({
  105. durationMs: 1000,
  106. result: "success",
  107. model: "custom:%E5%86%85%E7%BD%91%E4%BB%A3%E7%90%86:secret-model",
  108. talkId: "t1",
  109. });
  110. const model = reporter.calls[0]?.properties?.model;
  111. expect(model).toBe("custom");
  112. expect(String(model)).not.toContain("secret-model");
  113. });
  114. it("supervisor 投影出的旧报表身份复合值与编码值保留白名单模型", () => {
  115. const reporter = makeReporter();
  116. setUiPerfArmsReporter(reporter);
  117. reportUiFirstToken({ ttftMs: 800, model: "builtin:zai-start-plan/GLM-5.3", talkId: "t1" });
  118. reportUiFirstToken({
  119. ttftMs: 800,
  120. model: "custom:builtin%3Azai-start-plan:glm-5.3",
  121. talkId: "t1",
  122. });
  123. expect(reporter.calls.map((call) => call.properties?.model)).toEqual(["glm-5.3", "glm-5.3"]);
  124. });
  125. it("model 缺失时保持留空,不引入 custom 噪音", () => {
  126. const reporter = makeReporter();
  127. setUiPerfArmsReporter(reporter);
  128. reportUiFirstToken({ ttftMs: 800, talkId: "t1" });
  129. expect(reporter.calls[0]?.properties?.model).toBeUndefined();
  130. });
  131. it("reportUiMessageComplete 带 result/model", () => {
  132. const reporter = makeReporter();
  133. setUiPerfArmsReporter(reporter);
  134. reportUiMessageComplete({
  135. durationMs: 5000,
  136. result: "success",
  137. model: "glm-4.6",
  138. talkId: "t1",
  139. messageId: "m1",
  140. });
  141. expect(reporter.calls[0]).toMatchObject({
  142. name: "perf_ui_message_complete",
  143. group: UI_PERF_ARMS_GROUP,
  144. value: 5000,
  145. properties: {
  146. result: "success",
  147. model: "glm-4.6",
  148. talk_id: "t1",
  149. message_id: "m1",
  150. },
  151. });
  152. });
  153. it("reportUiTurnBreakdown 每轮只上报归因汇总字段", () => {
  154. const reporter = makeReporter();
  155. setUiPerfArmsReporter(reporter);
  156. reportUiTurnBreakdown({
  157. durationMs: 9000.4,
  158. result: "success",
  159. model: "glm-4.6",
  160. talkId: "task-1",
  161. messageId: "message-1",
  162. ttftMs: 1200.5,
  163. waitingMs: 300.4,
  164. toolCallTotal: 2,
  165. toolCallFailed: 1,
  166. agentStepCount: 4,
  167. retryCount: 1,
  168. fileChangeCount: 3,
  169. generatedCodeLines: 20,
  170. });
  171. expect(reporter.calls[0]).toEqual({
  172. name: UI_PERF_EVENT_TURN_BREAKDOWN,
  173. group: UI_PERF_ARMS_GROUP,
  174. value: 9000,
  175. properties: {
  176. result: "success",
  177. model: "glm-4.6",
  178. talk_id: "task-1",
  179. message_id: "message-1",
  180. duration_ms: 9000,
  181. ttft_ms: 1201,
  182. waiting_ms: 300,
  183. tool_call_total: 2,
  184. tool_call_failed: 1,
  185. agent_step_cnt: 4,
  186. retry_cnt: 1,
  187. file_change_cnt: 3,
  188. generated_code_lines: 20,
  189. },
  190. });
  191. });
  192. it("reportUiToolCallDetail 上报工具内部阶段耗时和脱敏聚合字段", () => {
  193. const reporter = makeReporter();
  194. setUiPerfArmsReporter(reporter);
  195. reportUiToolCallDetail({
  196. toolName: "Bash",
  197. status: "completed",
  198. talkId: "task-1",
  199. messageId: "message-1",
  200. toolCallId: "tool-1",
  201. parentToolCallId: "parent-tool-1",
  202. childToolCallId: "child-tool-1",
  203. childSessionId: "child-session-1",
  204. agentId: "agent-1",
  205. agentType: "Explore",
  206. totalMs: 1500,
  207. permissionWaitMs: 120,
  208. commandRunMs: 1300,
  209. firstOutputMs: 40,
  210. noOutputMs: 40,
  211. exitCode: 0,
  212. timedOut: false,
  213. outputBytes: 512,
  214. commandCategory: "test",
  215. commandName: "npm",
  216. commandCount: 1,
  217. commandStatus: "completed",
  218. fsReadMs: 1,
  219. fsWriteMs: 2,
  220. patchMatchMs: 3,
  221. fileCount: 1,
  222. totalBytes: 100,
  223. maxFileBytes: 100,
  224. hunkCount: 2,
  225. matchAttempts: 1,
  226. workspaceKind: "local",
  227. });
  228. expect(reporter.calls[0]).toEqual({
  229. name: UI_PERF_EVENT_TOOL_CALL_DETAIL,
  230. group: UI_PERF_ARMS_GROUP,
  231. value: 1500,
  232. properties: {
  233. tool_name: "Bash",
  234. status: "completed",
  235. talk_id: "task-1",
  236. message_id: "message-1",
  237. tool_call_id: "tool-1",
  238. parent_tool_call_id: "parent-tool-1",
  239. child_tool_call_id: "child-tool-1",
  240. child_session_id: "child-session-1",
  241. agent_id: "agent-1",
  242. agent_type: "Explore",
  243. total_ms: 1500,
  244. permission_wait_ms: 120,
  245. command_run_ms: 1300,
  246. first_output_ms: 40,
  247. no_output_ms: 40,
  248. exit_code: 0,
  249. timed_out: false,
  250. output_bytes: 512,
  251. command_category: "test",
  252. command_name: "npm",
  253. command_count: 1,
  254. command_status: "completed",
  255. fs_read_ms: 1,
  256. fs_write_ms: 2,
  257. patch_match_ms: 3,
  258. file_count: 1,
  259. total_bytes: 100,
  260. max_file_bytes: 100,
  261. hunk_count: 2,
  262. match_attempts: 1,
  263. workspace_kind: "local",
  264. },
  265. });
  266. });
  267. it("reporter 抛错被吞掉不向上传播", () => {
  268. const reporter = {
  269. reportArmsCustomEvent: vi.fn(() => {
  270. throw new Error("boom");
  271. }),
  272. };
  273. setUiPerfArmsReporter(reporter);
  274. expect(() => reportUiLaunchToInput(makeTimings())).not.toThrow();
  275. });
  276. });
  277. describe("agent step ARMS volume guard", () => {
  278. afterEach(() => {
  279. clearUiPerfArmsReporterForTest();
  280. });
  281. it("不再暴露逐 step ARMS 上报入口,避免长消息按 step 数放大 IPC 和自定义事件量", async () => {
  282. const telemetry = await import("@/lib/uiPerfArmsTelemetry.js");
  283. expect("reportUiAgentStep" in telemetry).toBe(false);
  284. });
  285. });
  286. describe("reportUiLaunchToInput: 7 段", () => {
  287. it("发 7 条,各段 value 正确,total = inputReady - createdAt", () => {
  288. const reporter = makeReporter();
  289. setUiPerfArmsReporter(reporter);
  290. reportUiLaunchToInput(makeTimings());
  291. expect(reporter.calls).toHaveLength(7);
  292. const byName = new Map(reporter.calls.map((c) => [c.name, c]));
  293. expect(byName.get(UI_PERF_EVENT_LAUNCH_TO_INPUT)).toMatchObject({
  294. group: UI_PERF_ARMS_GROUP,
  295. value: 2820,
  296. properties: { session_id: "sess-1" },
  297. });
  298. expect(byName.get(UI_PERF_EVENT_LAUNCH_ELECTRON_INIT)?.value).toBe(600);
  299. expect(byName.get(UI_PERF_EVENT_LAUNCH_REACT_COMMIT)?.value).toBe(75);
  300. expect(byName.get(UI_PERF_EVENT_LAUNCH_STARTUP_GATE)?.value).toBe(815);
  301. });
  302. it("某段为负(时钟回拨/跨进程偏移)→ 整批丢弃", () => {
  303. const reporter = makeReporter();
  304. setUiPerfArmsReporter(reporter);
  305. // appReady 早于 mainStart:app_ready 段为负,整批丢弃
  306. reportUiLaunchToInput(makeTimings({ appReady: 1500, mainStart: 1600 }));
  307. expect(reporter.calls).toHaveLength(0);
  308. });
  309. it("总时长超哨兵阈值 → 整批不发", () => {
  310. const reporter = makeReporter();
  311. setUiPerfArmsReporter(reporter);
  312. reportUiLaunchToInput(makeTimings({ inputReady: 1000 + LAUNCH_TO_INPUT_SANITY_MAX_MS + 1 }));
  313. expect(reporter.calls).toHaveLength(0);
  314. });
  315. });
  316. describe("stream stall", () => {
  317. it("首个 chunk 不上报(无前序)", () => {
  318. const reporter = makeReporter();
  319. setUiPerfArmsReporter(reporter);
  320. recordStreamChunkArrival("t1", { now: 1000 });
  321. expect(reporter.calls).toHaveLength(0);
  322. });
  323. it("间隔未超阈值不上报", () => {
  324. const reporter = makeReporter();
  325. setUiPerfArmsReporter(reporter);
  326. recordStreamChunkArrival("t1", { now: 1000 });
  327. recordStreamChunkArrival("t1", {
  328. now: 1000 + STREAM_STALL_REPORT_THRESHOLD_MS,
  329. });
  330. expect(reporter.calls).toHaveLength(0);
  331. });
  332. it("间隔超阈值上报真实时长", () => {
  333. const reporter = makeReporter();
  334. setUiPerfArmsReporter(reporter);
  335. recordStreamChunkArrival("t1", { now: 1000 });
  336. recordStreamChunkArrival("t1", {
  337. now: 1000 + STREAM_STALL_REPORT_THRESHOLD_MS + 500,
  338. waitingTool: true,
  339. messageId: "m1",
  340. model: "glm-4.6",
  341. chunkType: "thought",
  342. });
  343. expect(reporter.calls).toHaveLength(1);
  344. expect(reporter.calls[0]).toMatchObject({
  345. name: "perf_ui_stream_stall",
  346. value: STREAM_STALL_REPORT_THRESHOLD_MS + 500,
  347. properties: {
  348. waiting_tool: true,
  349. model: "glm-4.6",
  350. talk_id: "t1",
  351. message_id: "m1",
  352. chunk_type: "thought",
  353. },
  354. });
  355. });
  356. it("messageId 缺省时 message_id 留空", () => {
  357. const reporter = makeReporter();
  358. setUiPerfArmsReporter(reporter);
  359. recordStreamChunkArrival("t1", { now: 1000 });
  360. recordStreamChunkArrival("t1", {
  361. now: 1000 + STREAM_STALL_REPORT_THRESHOLD_MS + 500,
  362. });
  363. expect(reporter.calls[0]?.properties?.message_id).toBeUndefined();
  364. });
  365. it("clearStreamStallTracking 后重置(下一个 chunk 视为首个)", () => {
  366. const reporter = makeReporter();
  367. setUiPerfArmsReporter(reporter);
  368. recordStreamChunkArrival("t1", { now: 1000 });
  369. clearStreamStallTracking("t1");
  370. recordStreamChunkArrival("t1", { now: 100000 });
  371. expect(reporter.calls).toHaveLength(0);
  372. });
  373. });
  374. describe("input lag - shouldReportInputLag", () => {
  375. it("低于阈值不上报", () => {
  376. expect(
  377. shouldReportInputLag({
  378. lagMs: INPUT_LAG_REPORT_THRESHOLD_MS,
  379. isProgrammatic: false,
  380. isComposing: false,
  381. }),
  382. ).toBe(false);
  383. });
  384. it("超过阈值上报", () => {
  385. expect(
  386. shouldReportInputLag({
  387. lagMs: INPUT_LAG_REPORT_THRESHOLD_MS + 1,
  388. isProgrammatic: false,
  389. isComposing: false,
  390. }),
  391. ).toBe(true);
  392. });
  393. it("超过哨兵上限不上报", () => {
  394. expect(
  395. shouldReportInputLag({
  396. lagMs: INPUT_LAG_SANITY_MAX_MS + 1,
  397. isProgrammatic: false,
  398. isComposing: false,
  399. }),
  400. ).toBe(false);
  401. });
  402. it("程序化改写即使超阈也不上报", () => {
  403. expect(
  404. shouldReportInputLag({
  405. lagMs: INPUT_LAG_REPORT_THRESHOLD_MS + 1000,
  406. isProgrammatic: true,
  407. isComposing: false,
  408. }),
  409. ).toBe(false);
  410. });
  411. it("IME 组合态即使超阈也不上报", () => {
  412. expect(
  413. shouldReportInputLag({
  414. lagMs: INPUT_LAG_REPORT_THRESHOLD_MS + 1000,
  415. isProgrammatic: false,
  416. isComposing: true,
  417. }),
  418. ).toBe(false);
  419. });
  420. });
  421. describe("input lag - recordInputLag", () => {
  422. it("超阈上报,payload 字段正确", () => {
  423. const reporter = makeReporter();
  424. setUiPerfArmsReporter(reporter);
  425. recordInputLag({
  426. lagMs: 642.7,
  427. textLength: 1280,
  428. isProgrammatic: false,
  429. isComposing: false,
  430. taskId: "t1",
  431. });
  432. expect(reporter.calls).toHaveLength(1);
  433. expect(reporter.calls[0]).toMatchObject({
  434. name: UI_PERF_EVENT_INPUT_LAG,
  435. group: UI_PERF_ARMS_GROUP,
  436. value: 643,
  437. properties: {
  438. lag_ms: 643,
  439. text_length: 1280,
  440. task_id: "t1",
  441. },
  442. });
  443. });
  444. it("不满足上报条件时静默", () => {
  445. const reporter = makeReporter();
  446. setUiPerfArmsReporter(reporter);
  447. recordInputLag({
  448. lagMs: 100,
  449. textLength: 5,
  450. isProgrammatic: false,
  451. isComposing: false,
  452. });
  453. expect(reporter.calls).toHaveLength(0);
  454. });
  455. it("无 reporter 时不抛", () => {
  456. clearUiPerfArmsReporterForTest();
  457. expect(() =>
  458. recordInputLag({
  459. lagMs: 9999,
  460. textLength: 10,
  461. isProgrammatic: false,
  462. isComposing: false,
  463. }),
  464. ).not.toThrow();
  465. });
  466. it("reporter 抛错时只 warn 不向上传播", () => {
  467. const reporter = {
  468. reportArmsCustomEvent: vi.fn(() => {
  469. throw new Error("boom");
  470. }),
  471. };
  472. setUiPerfArmsReporter(reporter);
  473. expect(() =>
  474. recordInputLag({
  475. lagMs: INPUT_LAG_REPORT_THRESHOLD_MS + 1000,
  476. textLength: 10,
  477. isProgrammatic: false,
  478. isComposing: false,
  479. }),
  480. ).not.toThrow();
  481. expect(reporter.reportArmsCustomEvent).toHaveBeenCalledTimes(1);
  482. });
  483. });