messageTelemetry.test.ts 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. import { readFileSync } from "node:fs";
  2. import { afterEach, describe, expect, it } from "vitest";
  3. import {
  4. buildConversationRewindTelemetryEvent,
  5. buildPermissionPromptResultTelemetryEvent,
  6. buildWorkflowRunResultTelemetryEvent,
  7. ConversationTelemetryEngine,
  8. createPermissionPromptShownClock,
  9. resolveConversationRewindTarget,
  10. resolveSendAckSettlement,
  11. WORKFLOW_RUN_RESULT_STATUSES,
  12. WORKFLOW_RUN_STOP_REASONS,
  13. } from "@zcode/shared/conversation-telemetry";
  14. import { resetMessageTelemetryForTest } from "@zcode/shared/conversation-telemetry/messageTelemetry";
  15. import {
  16. normalizeToolErrorCode,
  17. sanitizeTelemetryEventDetail,
  18. sanitizeToolErrorCode,
  19. } from "@zcode/shared";
  20. import type { ConversationTelemetryInput } from "@zcode/shared/zcode-protocol-v4";
  21. describe("message 首响时序与独立通知", () => {
  22. const engines: ConversationTelemetryEngine[] = [];
  23. afterEach(() => {
  24. for (const engine of engines.splice(0)) engine.dispose();
  25. resetMessageTelemetryForTest();
  26. });
  27. function setup(start = true) {
  28. const reports: Array<{ elementName: string; eventExtraDetail: Record<string, string> }> = [];
  29. let seq = 0;
  30. const engine = new ConversationTelemetryEngine({
  31. workspaceScopeKey: "test",
  32. now: () => 100 + seq,
  33. platform: { reportTelemetryEvent: async () => {}, reportArmsCustomEvent: async () => {} },
  34. reportEvent: async (report) => {
  35. reports.push(report);
  36. },
  37. });
  38. engines.push(engine);
  39. engine.acceptPromptSeed({
  40. sessionId: "s",
  41. sourceCommandId: "c",
  42. sendTime: 100,
  43. extraDetail: {},
  44. });
  45. const fact = (fields: Record<string, unknown>) =>
  46. engine.handleFact({
  47. version: 1,
  48. sessionId: "s",
  49. sourceCommandId: "c",
  50. turnId: "t",
  51. eventId: `e${++seq}`,
  52. eventSeq: seq,
  53. occurredAt: 100 + seq,
  54. ...fields,
  55. } as ConversationTelemetryInput);
  56. if (start) fact({ kind: "turn.started" });
  57. const request = (requestId: string, querySource = "main_turn") =>
  58. fact({
  59. kind: "model.request.status",
  60. requestId,
  61. status: "model_request_started",
  62. providerId: "p",
  63. modelId: "m",
  64. querySource,
  65. transport: "http",
  66. attempt: 1,
  67. maxAttempts: 2,
  68. });
  69. const metrics = (
  70. requestId: string,
  71. inputTokens = 100,
  72. cacheReadTokens: number | undefined = 20,
  73. querySource = "main_turn",
  74. ) =>
  75. fact({
  76. kind: "model.request.metrics",
  77. requestId,
  78. providerId: "p",
  79. modelId: "m",
  80. querySource,
  81. durationMs: 5,
  82. inputTokens,
  83. cacheReadTokens,
  84. });
  85. const output = () =>
  86. fact({ kind: "stream.chunk", channel: "text", firstChunk: true, chunkLength: 4 });
  87. const finish = async () => {
  88. fact({ kind: "turn.terminal", status: "success" });
  89. await engine.flushReportsForTest();
  90. return reports.find((r) => r.elementName === "message_completion")!.eventExtraDetail;
  91. };
  92. return { fact, request, metrics, output, finish, engine, reports };
  93. }
  94. it("A 无输出后重试 B,A 迟到 metrics 不污染 B", async () => {
  95. const t = setup();
  96. t.request("A");
  97. t.request("B");
  98. t.output();
  99. t.metrics("A", 900);
  100. t.metrics("B", 100);
  101. expect(await t.finish()).toMatchObject({
  102. ttft_request_id: "B",
  103. ttft_input_tokens: "100",
  104. ttft_cached_input_tokens: "20",
  105. });
  106. });
  107. it("metrics 先于 tool_call,工具首响保留同请求 usage", async () => {
  108. const t = setup();
  109. t.request("A");
  110. t.metrics("A", 100, 0);
  111. t.fact({ kind: "tool.lifecycle", phase: "started", toolCallId: "tool", toolName: "Read" });
  112. expect(await t.finish()).toMatchObject({
  113. ttft_request_id: "A",
  114. ttft_output_kind: "tool",
  115. ttft_input_tokens: "100",
  116. ttft_cached_input_tokens: "0",
  117. });
  118. });
  119. it("首响冻结后 B 先完成、A 后完成,仍只取 A", async () => {
  120. const t = setup();
  121. t.request("A");
  122. t.output();
  123. t.request("B");
  124. t.metrics("B", 900);
  125. t.metrics("A", 100);
  126. expect(await t.finish()).toMatchObject({ ttft_request_id: "A", ttft_input_tokens: "100" });
  127. });
  128. it("没有输出时不把收到的 metrics 当成首响", async () => {
  129. const t = setup();
  130. t.request("A");
  131. t.metrics("A");
  132. expect(await t.finish()).toMatchObject({
  133. time_to_first_token: "-1",
  134. ttft_output_kind: "none",
  135. ttft_request_id: "",
  136. ttft_input_tokens: "",
  137. ttft_cached_input_tokens: "",
  138. });
  139. });
  140. it.each(["compact", "session_title", "subagent"])(
  141. "%s 请求不切候选,metrics 不污染主轮",
  142. async (source) => {
  143. const t = setup();
  144. t.request("A");
  145. t.request("side", source);
  146. t.metrics("side", 900, 800, source);
  147. t.output();
  148. t.metrics("A");
  149. expect(await t.finish()).toMatchObject({ ttft_request_id: "A", ttft_input_tokens: "100" });
  150. },
  151. );
  152. it("旧 CLI 只有 usage.delta 时仍可完成,首响 token 不猜累计值", async () => {
  153. const t = setup();
  154. t.request("A");
  155. t.output();
  156. t.fact({
  157. kind: "usage.delta",
  158. requestId: "A",
  159. inputTokens: 900,
  160. outputTokens: 2,
  161. totalTokens: 902,
  162. reasoningTokens: 0,
  163. cacheReadTokens: 0,
  164. cacheWriteTokens: 0,
  165. });
  166. expect(await t.finish()).toMatchObject({
  167. is_first_message: "unknown",
  168. send_mode: "unknown",
  169. input_tokens: "900",
  170. ttft_input_tokens: "",
  171. ttft_cached_input_tokens: "",
  172. });
  173. });
  174. it.each([true, false])(
  175. "admission 在 started 之前=%s,共用 eventId 不互相去重",
  176. async (before) => {
  177. const t = setup(false);
  178. const admission = () =>
  179. t.fact({
  180. kind: "turn.admission",
  181. eventId: "start",
  182. isFirstMessage: false,
  183. sendMode: "queued",
  184. });
  185. if (before) admission();
  186. t.fact({ kind: "turn.started", eventId: "start" });
  187. if (!before) admission();
  188. t.request("A");
  189. t.output();
  190. t.fact({
  191. kind: "model.request.status",
  192. eventId: "complete",
  193. status: "model_request_completed",
  194. requestId: "A",
  195. providerId: "p",
  196. modelId: "m",
  197. transport: "http",
  198. durationMs: 5,
  199. });
  200. t.fact({
  201. kind: "model.request.metrics",
  202. eventId: "complete",
  203. requestId: "A",
  204. providerId: "p",
  205. modelId: "m",
  206. durationMs: 5,
  207. inputTokens: 100,
  208. });
  209. const detail = await t.finish();
  210. expect(detail).toMatchObject({
  211. is_first_message: "0",
  212. send_mode: "queued",
  213. ttft_input_tokens: "100",
  214. ttft_cached_input_tokens: "",
  215. });
  216. t.metrics("A", 900);
  217. await t.engine.flushReportsForTest();
  218. expect(t.reports.filter((r) => r.elementName === "message_completion")).toHaveLength(1);
  219. expect(detail.ttft_input_tokens).toBe("100");
  220. expect(
  221. t.reports.find((r) => r.elementName === "send_btn")!.eventExtraDetail,
  222. ).not.toHaveProperty("send_mode");
  223. for (const r of t.reports.filter((r) => r.elementName === "agent_step"))
  224. expect(r.eventExtraDetail).not.toHaveProperty("is_first_message");
  225. },
  226. );
  227. it("child 请求即使复用 requestId 也不能覆盖父轮首响", async () => {
  228. const t = setup();
  229. t.request("A");
  230. t.output();
  231. t.metrics("A", 100, 20);
  232. t.fact({
  233. kind: "subagent.lifecycle",
  234. phase: "spawned",
  235. agentId: "agent",
  236. childSessionId: "child",
  237. parentToolCallId: "tool",
  238. background: false,
  239. });
  240. t.fact({
  241. kind: "model.request.metrics",
  242. sessionId: "child",
  243. requestId: "A",
  244. providerId: "p",
  245. modelId: "m",
  246. querySource: "main_turn",
  247. durationMs: 5,
  248. inputTokens: 900,
  249. cacheReadTokens: 800,
  250. });
  251. t.fact({
  252. kind: "subagent.lifecycle",
  253. phase: "stopped",
  254. agentId: "agent",
  255. childSessionId: "child",
  256. parentToolCallId: "tool",
  257. background: false,
  258. });
  259. expect(await t.finish()).toMatchObject({
  260. ttft_request_id: "A",
  261. ttft_input_tokens: "100",
  262. ttft_cached_input_tokens: "20",
  263. });
  264. });
  265. });
  266. describe("编辑重发与回退埋点", () => {
  267. const engines: ConversationTelemetryEngine[] = [];
  268. afterEach(() => {
  269. for (const engine of engines.splice(0)) engine.dispose();
  270. resetMessageTelemetryForTest();
  271. });
  272. it("send_type 随 seed 冻结到 send_btn、completion 和每条 step", async () => {
  273. const reports: Array<{ elementName: string; eventExtraDetail: Record<string, string> }> = [];
  274. let seq = 0;
  275. const engine = new ConversationTelemetryEngine({
  276. workspaceScopeKey: "test",
  277. now: () => 100 + seq,
  278. platform: { reportTelemetryEvent: async () => {}, reportArmsCustomEvent: async () => {} },
  279. reportEvent: async (report) => {
  280. reports.push(report);
  281. },
  282. });
  283. engines.push(engine);
  284. engine.acceptPromptSeed({
  285. sessionId: "s",
  286. sourceCommandId: "edit-cmd",
  287. sendTime: 100,
  288. extraDetail: { message_source: "chat", send_type: "edit" },
  289. });
  290. const fact = (fields: Record<string, unknown>) =>
  291. engine.handleFact({
  292. version: 1,
  293. sessionId: "s",
  294. sourceCommandId: "edit-cmd",
  295. turnId: "t",
  296. eventId: `e${++seq}`,
  297. eventSeq: seq,
  298. occurredAt: 100 + seq,
  299. ...fields,
  300. } as ConversationTelemetryInput);
  301. fact({ kind: "turn.started" });
  302. fact({ kind: "tool.lifecycle", phase: "started", toolCallId: "tool", toolName: "Read" });
  303. fact({ kind: "tool.lifecycle", phase: "completed", toolCallId: "tool", toolName: "Read" });
  304. fact({ kind: "turn.terminal", status: "success" });
  305. await engine.flushReportsForTest();
  306. const names = reports.map((r) => r.elementName);
  307. expect(names).toContain("send_btn");
  308. expect(names).toContain("message_completion");
  309. expect(names).toContain("agent_step");
  310. for (const r of reports) expect(r.eventExtraDetail.send_type).toBe("edit");
  311. });
  312. it("文件冲突的编辑 ACK 直接落定 blocked,不进入待渲染", () => {
  313. expect(
  314. resolveSendAckSettlement({
  315. status: "accepted",
  316. result: { type: "editUserQuery", disposition: "blocked" },
  317. }),
  318. ).toEqual({ kind: "settle", status: "fail", ackStatus: "accepted", reasonCode: "blocked" });
  319. expect(
  320. resolveSendAckSettlement({
  321. status: "accepted",
  322. result: { type: "editUserQuery", disposition: "rewind" },
  323. }),
  324. ).toEqual({ kind: "awaitRender", ackStatus: "accepted" });
  325. });
  326. const rows = [
  327. {
  328. kind: "turnHeader",
  329. rowId: 1,
  330. turnId: "t1",
  331. sourceCommandId: "c1",
  332. state: "completedSuccess",
  333. },
  334. { kind: "userInput", rowId: 2, turnId: "t1" },
  335. {
  336. kind: "turnHeader",
  337. rowId: 10,
  338. turnId: "t2",
  339. sourceCommandId: "c2",
  340. state: "failed",
  341. fileChanges: { files: 3 },
  342. },
  343. { kind: "userInput", rowId: 11, turnId: "t2" },
  344. { kind: "assistant", rowId: 12, turnId: "t2" },
  345. { kind: "turnHeader", rowId: 20, turnId: "t3", sourceCommandId: "c3", state: "running" },
  346. ];
  347. it("目标轮取自用户行所在 turnHeader,丢弃轮数含其后全部轮次", () => {
  348. expect(resolveConversationRewindTarget(rows, 11)).toEqual({
  349. targetMessageId: "c2",
  350. targetTurnState: "failed",
  351. targetTurnFiles: "3",
  352. discardedTurns: 2,
  353. });
  354. expect(resolveConversationRewindTarget(rows, 99)).toEqual({
  355. targetMessageId: "",
  356. targetTurnState: "unknown",
  357. targetTurnFiles: "",
  358. discardedTurns: 0,
  359. });
  360. });
  361. it("编辑重发:accepted / blocked / rejected 与原因白名单", () => {
  362. const target = resolveConversationRewindTarget(rows, 11);
  363. const base = { action: "edit_resend" as const, sessionId: "s", commandId: "cmd", target };
  364. const accepted = buildConversationRewindTelemetryEvent({
  365. ...base,
  366. workspaceMode: "rewind",
  367. ack: { status: "accepted", result: { type: "editUserQuery", disposition: "rewind" } },
  368. });
  369. expect(accepted).toMatchObject({
  370. elementName: "conversation_rewind",
  371. eventRegion: "chat",
  372. eventType: "result",
  373. talkId: "s",
  374. messageId: "cmd",
  375. });
  376. expect(accepted.eventExtraDetail).toEqual({
  377. action: "edit_resend",
  378. workspace_mode: "rewind",
  379. result: "accepted",
  380. ack_status: "accepted",
  381. blocked_reason: "",
  382. target_message_id: "c2",
  383. target_turn_state: "failed",
  384. target_turn_files: "3",
  385. discarded_turns: "2",
  386. restored_files: "",
  387. });
  388. const blocked = (reasonCode: string) =>
  389. buildConversationRewindTelemetryEvent({
  390. ...base,
  391. workspaceMode: "rewind",
  392. ack: {
  393. status: "accepted",
  394. result: { type: "editUserQuery", disposition: "blocked", reasonCode },
  395. },
  396. }).eventExtraDetail;
  397. expect(blocked("guard.workspaceRewindUnsafeFiles")).toMatchObject({
  398. result: "blocked",
  399. blocked_reason: "unsafe_files",
  400. });
  401. // 未知 reasonCode 不原样透传。
  402. expect(blocked("guard.somethingNew /secret/path")).toMatchObject({ blocked_reason: "other" });
  403. expect(
  404. buildConversationRewindTelemetryEvent({ ...base, ack: { status: "stale" } }).eventExtraDetail,
  405. ).toMatchObject({ result: "rejected", ack_status: "stale", workspace_mode: "preserve" });
  406. expect(
  407. buildConversationRewindTelemetryEvent({ ...base, ack: { status: "weird" } }).eventExtraDetail
  408. .ack_status,
  409. ).toBe("other");
  410. });
  411. it("只撤销文件:只有 applied=true 才算成功并带文件数", () => {
  412. const target = resolveConversationRewindTarget(rows, 10);
  413. const event = (applied: boolean) =>
  414. buildConversationRewindTelemetryEvent({
  415. action: "file_only",
  416. sessionId: "s",
  417. commandId: "cmd",
  418. target,
  419. ack: {
  420. status: "accepted",
  421. result: { type: "applyFileRewind", applied, preview: { safeFiles: [{}, {}] } },
  422. },
  423. }).eventExtraDetail;
  424. expect(event(true)).toMatchObject({
  425. action: "file_only",
  426. workspace_mode: "",
  427. result: "accepted",
  428. restored_files: "2",
  429. discarded_turns: "",
  430. });
  431. expect(event(false)).toMatchObject({
  432. result: "blocked",
  433. blocked_reason: "not_applied",
  434. restored_files: "",
  435. });
  436. });
  437. });
  438. describe("授权弹窗结果埋点", () => {
  439. const base = {
  440. sessionId: "s",
  441. messageId: "cmd-1",
  442. toolName: "Write",
  443. toolCallId: "toolu_1",
  444. fromSubagent: false,
  445. askMode: "build",
  446. shownAt: 1_000,
  447. respondedAt: 6_500,
  448. ackStatus: "accepted",
  449. };
  450. it("V4 optionId 映射为稳定枚举,未知 optionId 按 kind 归类", () => {
  451. const option = (optionId: string, kind?: string) =>
  452. buildPermissionPromptResultTelemetryEvent({ ...base, option: { optionId, kind } })
  453. .eventExtraDetail.option;
  454. expect(option("allowOnce", "allowOnce")).toBe("allow_once");
  455. expect(option("allowAlways", "allowAlways")).toBe("allow_project");
  456. expect(option("allowSession", "allowAlways")).toBe("allow_session");
  457. expect(option("fullAccess", "custom")).toBe("allow_full_access");
  458. expect(option("allowAndSwitchGuarded")).toBe("allow_switch_guarded");
  459. expect(option("deny", "deny")).toBe("deny");
  460. expect(option("workflowRefine", "custom")).toBe("workflow_refine");
  461. expect(option("somethingNew", "allowAlways")).toBe("allow_always_other");
  462. expect(option("somethingNew", "custom")).toBe("other");
  463. });
  464. it("完整字段:等待时长、是否写理由、子 agent 来源", () => {
  465. const event = buildPermissionPromptResultTelemetryEvent({
  466. ...base,
  467. option: { optionId: "deny", kind: "deny" },
  468. feedback: " do not write ",
  469. fromSubagent: true,
  470. modeSwitch: "choose",
  471. });
  472. expect(event).toMatchObject({
  473. elementName: "permission_prompt_result",
  474. eventRegion: "chat",
  475. eventType: "result",
  476. talkId: "s",
  477. messageId: "cmd-1",
  478. });
  479. expect(event.eventExtraDetail).toEqual({
  480. option: "deny",
  481. has_feedback: "1",
  482. tool_name: "Write",
  483. tool_call_id: "toolu_1",
  484. from_subagent: "1",
  485. ask_mode: "build",
  486. mode_switch: "choose",
  487. wait_ms: "5500",
  488. ack: "accepted",
  489. });
  490. // 反馈正文不出现在任何字段里。
  491. expect(JSON.stringify(event)).not.toContain("do not write");
  492. });
  493. it("空白反馈不算写了理由;不合规标识与未知值不透传", () => {
  494. const detail = buildPermissionPromptResultTelemetryEvent({
  495. ...base,
  496. messageId: "",
  497. option: { optionId: "deny", kind: "deny" },
  498. feedback: " ",
  499. toolName: "Bash /etc/passwd",
  500. toolCallId: "x".repeat(200),
  501. askMode: undefined,
  502. modeSwitch: "weird",
  503. shownAt: undefined,
  504. ackStatus: "rejected",
  505. });
  506. expect(detail).not.toHaveProperty("messageId");
  507. expect(detail.eventExtraDetail).toMatchObject({
  508. has_feedback: "0",
  509. tool_name: "other",
  510. tool_call_id: "",
  511. ask_mode: "",
  512. mode_switch: "",
  513. wait_ms: "",
  514. ack: "failed",
  515. });
  516. // 批准时填写的反馈会被忽略,不算写了理由。
  517. expect(
  518. buildPermissionPromptResultTelemetryEvent({
  519. ...base,
  520. option: { optionId: "allowOnce" },
  521. feedback: "ignored",
  522. }).eventExtraDetail.has_feedback,
  523. ).toBe("0");
  524. // duplicate 视为已生效;noop(收件箱 / 网关判定无事可做)单列;其余都算失败。
  525. const ack = (ackStatus: string) =>
  526. buildPermissionPromptResultTelemetryEvent({
  527. ...base,
  528. option: { optionId: "deny" },
  529. ackStatus,
  530. }).eventExtraDetail.ack;
  531. expect([ack("duplicate"), ack("noop"), ack("failed"), ack("stale")]).toEqual([
  532. "accepted",
  533. "noop",
  534. "failed",
  535. "failed",
  536. ]);
  537. expect(
  538. buildPermissionPromptResultTelemetryEvent({
  539. ...base,
  540. toolName: "mcp__dbx__dbx_execute_query",
  541. option: { optionId: "allowOnce" },
  542. }).eventExtraDetail.tool_name,
  543. ).toBe("mcp__dbx__dbx_execute_query");
  544. });
  545. it("首次出现时间按 interaction 记录:切走再回来不重置,超出上限丢最早的", () => {
  546. const clock = createPermissionPromptShownClock(2);
  547. clock.markShown("p1", 1_000);
  548. // 切到别的会话(p2 出现)再回到 p1:p1 仍按首次出现计时。
  549. clock.markShown("p2", 2_000);
  550. clock.markShown("p1", 9_000);
  551. expect(clock.claimReport("p1", "failed")).toEqual({ report: true, shownAt: 1_000 });
  552. clock.markShown("p3", 3_000);
  553. // 上限 2:p1、p2、p3 中最早的 p1 被丢弃。
  554. expect(clock.claimReport("p1", "failed")).toEqual({ report: true, shownAt: undefined });
  555. expect(clock.claimReport("p3", "failed")).toEqual({ report: true, shownAt: 3_000 });
  556. });
  557. it("claimReport:accepted 后收口,重复应答不再上报、不再计时;failed / noop 不收口", () => {
  558. const clock = createPermissionPromptShownClock();
  559. clock.markShown("dup", 1_000);
  560. expect(clock.claimReport("dup", "accepted")).toEqual({ report: true, shownAt: 1_000 });
  561. // 弹窗消失前的双击 / 连点:CLI 仍返回 accepted,但不再上报。
  562. clock.markShown("dup", 1_100);
  563. expect(clock.claimReport("dup", "accepted")).toEqual({ report: false });
  564. expect(clock.claimReport("dup", "failed")).toEqual({ report: false });
  565. // failed → accepted:两次都上报,沿用同一起点。
  566. clock.markShown("retry", 2_000);
  567. expect(clock.claimReport("retry", "failed")).toEqual({ report: true, shownAt: 2_000 });
  568. clock.markShown("retry", 2_500);
  569. expect(clock.claimReport("retry", "accepted")).toEqual({ report: true, shownAt: 2_000 });
  570. expect(clock.claimReport("retry", "duplicate")).toEqual({ report: false });
  571. // noop 不能证明应答已送达:之后的有效应答照常上报。
  572. clock.markShown("noop", 3_000);
  573. expect(clock.claimReport("noop", "noop")).toEqual({ report: true, shownAt: 3_000 });
  574. expect(clock.claimReport("noop", "accepted")).toEqual({ report: true, shownAt: 3_000 });
  575. expect(clock.claimReport("noop", "accepted")).toEqual({ report: false });
  576. });
  577. });
  578. describe("工具失败原因码 agent_step.error_code", () => {
  579. const engines: ConversationTelemetryEngine[] = [];
  580. afterEach(() => {
  581. for (const engine of engines.splice(0)) engine.dispose();
  582. resetMessageTelemetryForTest();
  583. });
  584. it("白名单归一:命名 code 转小写,1–4 位数字写成 h<数字>,其余 other,缺失 unknown", () => {
  585. expect(normalizeToolErrorCode("TOOL_TIMEOUT")).toBe("tool_timeout");
  586. expect(normalizeToolErrorCode("tool_timeout")).toBe("tool_timeout");
  587. expect(normalizeToolErrorCode(" INVALID_INPUT ")).toBe("invalid_input");
  588. expect(normalizeToolErrorCode("TOOL_EXECUTION_FAILED")).toBe("tool_execution_failed");
  589. expect(normalizeToolErrorCode("agent_child_runtime_failed")).toBe("agent_child_runtime_failed");
  590. expect(normalizeToolErrorCode("8")).toBe("h8");
  591. expect(normalizeToolErrorCode("1302")).toBe("h1302");
  592. expect(normalizeToolErrorCode("12345")).toBe("other");
  593. expect(normalizeToolErrorCode("-32001")).toBe("other");
  594. expect(normalizeToolErrorCode("webfetch_fetch_failed")).toBe("other");
  595. expect(normalizeToolErrorCode("Error")).toBe("other");
  596. expect(normalizeToolErrorCode("ENOENT: no such file '/home/u/secret.txt'")).toBe("other");
  597. expect(normalizeToolErrorCode("")).toBe("unknown");
  598. expect(normalizeToolErrorCode(undefined)).toBe("unknown");
  599. });
  600. it("白名单与 CLI 的 CoreErrorType、AgentErrorCode 和 fact 里写死的 code 同步", () => {
  601. const cliSource = (path: string) =>
  602. readFileSync(new URL(`../../../apps/zcode-cli/packages/${path}`, import.meta.url), "utf8");
  603. const constValues = (source: string, name: string) => {
  604. const body = new RegExp(`export const ${name} = \\{([\\s\\S]*?)\\} as const;`, "u").exec(
  605. source,
  606. )?.[1];
  607. return [...(body ?? "").matchAll(/:\s*"([a-z_]+)"/gu)].map((m) => m[1]!);
  608. };
  609. const agentCodes = constValues(cliSource("contracts/src/tools/agent.ts"), "AgentErrorCode");
  610. expect(agentCodes).toHaveLength(4);
  611. for (const code of agentCodes) {
  612. expect(normalizeToolErrorCode(code)).toBe(code);
  613. expect(sanitizeToolErrorCode(code)).toBe(code);
  614. }
  615. // fact 归一器里写死的 errorCode(如被用户停止的 turn 的 USER_INTERRUPT)同样要能识别。
  616. const factCodes = [
  617. ...cliSource("bootstrap/src/zcode-protocol-v4/conversation-telemetry-facts.ts").matchAll(
  618. /errorCode: "([A-Z_]+)"/gu,
  619. ),
  620. ].map((m) => m[1]!);
  621. expect(factCodes.length).toBeGreaterThan(0);
  622. for (const code of factCodes) {
  623. expect(normalizeToolErrorCode(code)).toBe(code.toLowerCase());
  624. }
  625. const source = cliSource("contracts/src/errors/index.ts");
  626. const block = /export const CoreErrorType = \{([\s\S]*?)\} as const;/u.exec(source)?.[1] ?? "";
  627. const types = [...block.matchAll(/:\s*"([a-z_]+)"/gu)].map((m) => m[1]!);
  628. expect(types).toHaveLength(27);
  629. for (const type of types) {
  630. expect(normalizeToolErrorCode(type.toUpperCase())).toBe(type);
  631. expect(sanitizeToolErrorCode(type)).toBe(type);
  632. }
  633. });
  634. it("出网兜底只放行归一后的取值,且幂等", () => {
  635. for (const raw of ["TOOL_TIMEOUT", "8", "x", undefined, "agent_unknown_type"]) {
  636. const normalized = normalizeToolErrorCode(raw);
  637. expect(sanitizeToolErrorCode(normalized)).toBe(normalized);
  638. }
  639. expect(sanitizeToolErrorCode("")).toBe("");
  640. expect(sanitizeToolErrorCode("TOOL_TIMEOUT")).toBe("other");
  641. expect(sanitizeToolErrorCode("8")).toBe("other");
  642. expect(sanitizeToolErrorCode("h12345")).toBe("other");
  643. expect(sanitizeToolErrorCode("/Users/me/.ssh/id_rsa")).toBe("other");
  644. expect(
  645. sanitizeTelemetryEventDetail("agent_step", {
  646. error_code: "ENOENT /home/u/a.txt",
  647. error_msg: "ENOENT /home/u/a.txt",
  648. }),
  649. ).toMatchObject({ error_code: "other", error_msg: "[redacted]" });
  650. expect(sanitizeTelemetryEventDetail("agent_step", { error_code: "h8" }).error_code).toBe("h8");
  651. // 其他事件同名字段(自动化创建结果)不受影响。
  652. expect(
  653. sanitizeTelemetryEventDetail("automation_create_result", { error_code: "limit" }).error_code,
  654. ).toBe("limit");
  655. });
  656. function setup() {
  657. const reports: Array<{ elementName: string; eventExtraDetail: Record<string, string> }> = [];
  658. let seq = 0;
  659. const engine = new ConversationTelemetryEngine({
  660. workspaceScopeKey: "test",
  661. now: () => 100 + seq,
  662. platform: { reportTelemetryEvent: async () => {}, reportArmsCustomEvent: async () => {} },
  663. reportEvent: async (report) => {
  664. reports.push(report);
  665. },
  666. });
  667. engines.push(engine);
  668. engine.acceptPromptSeed({
  669. sessionId: "s",
  670. sourceCommandId: "c",
  671. sendTime: 100,
  672. extraDetail: {},
  673. });
  674. const fact = (fields: Record<string, unknown>) =>
  675. engine.handleFact({
  676. version: 1,
  677. sessionId: "s",
  678. sourceCommandId: "c",
  679. turnId: "t",
  680. eventId: `e${++seq}`,
  681. eventSeq: seq,
  682. occurredAt: 100 + seq,
  683. ...fields,
  684. } as ConversationTelemetryInput);
  685. const steps = async () => {
  686. await engine.flushReportsForTest();
  687. return reports.filter((r) => r.elementName === "agent_step").map((r) => r.eventExtraDetail);
  688. };
  689. fact({ kind: "turn.started" });
  690. return { fact, steps };
  691. }
  692. it("CLI 工具终态的 errorCode 一路带到失败 tool step;成功和非工具 step 为空串", async () => {
  693. const t = setup();
  694. t.fact({ kind: "stream.chunk", channel: "text", firstChunk: true, chunkLength: 4 });
  695. t.fact({ kind: "tool.lifecycle", phase: "started", toolCallId: "edit", toolName: "Edit" });
  696. t.fact({
  697. kind: "tool.lifecycle",
  698. phase: "failed",
  699. toolCallId: "edit",
  700. toolName: "Edit",
  701. errorCode: "8",
  702. errorMessage: "String to replace not found in /home/u/a.ts",
  703. });
  704. t.fact({ kind: "tool.lifecycle", phase: "started", toolCallId: "fetch", toolName: "WebFetch" });
  705. t.fact({
  706. kind: "tool.lifecycle",
  707. phase: "failed",
  708. toolCallId: "fetch",
  709. toolName: "WebFetch",
  710. errorCode: "TOOL_TIMEOUT",
  711. errorMessage: "timed out",
  712. });
  713. t.fact({ kind: "tool.lifecycle", phase: "started", toolCallId: "bare", toolName: "Bash" });
  714. t.fact({ kind: "tool.lifecycle", phase: "failed", toolCallId: "bare", toolName: "Bash" });
  715. t.fact({ kind: "tool.lifecycle", phase: "started", toolCallId: "read", toolName: "Read" });
  716. t.fact({ kind: "tool.lifecycle", phase: "completed", toolCallId: "read", toolName: "Read" });
  717. t.fact({ kind: "turn.terminal", status: "success" });
  718. const steps = await t.steps();
  719. const byTool = (name: string) => steps.find((s) => s.tool_name === name)!;
  720. expect(byTool("Edit")).toMatchObject({
  721. status: "fail",
  722. error_type: "TOOL_EXEC_ERROR",
  723. error_code: "h8",
  724. });
  725. expect(byTool("WebFetch")).toMatchObject({ status: "fail", error_code: "tool_timeout" });
  726. expect(byTool("Bash")).toMatchObject({ status: "fail", error_code: "unknown" });
  727. expect(byTool("Read")).toMatchObject({ status: "success", error_code: "" });
  728. const generation = steps.find((s) => s.step_type === "generation")!;
  729. expect(generation.error_code).toBe("");
  730. for (const step of steps) expect(Object.hasOwn(step, "error_code")).toBe(true);
  731. });
  732. it("整轮失败时被一并关闭的工具 step 没有工具级 code,记 unknown", async () => {
  733. const t = setup();
  734. t.fact({ kind: "tool.lifecycle", phase: "started", toolCallId: "bash", toolName: "Bash" });
  735. t.fact({ kind: "turn.terminal", status: "failed", errorCode: "MODEL_ERROR" });
  736. const steps = await t.steps();
  737. expect(steps.find((s) => s.tool_name === "Bash")).toMatchObject({
  738. status: "fail",
  739. error_code: "unknown",
  740. });
  741. });
  742. it("后台子 agent 的 Agent 汇总 step 取子会话 turn.terminal 的 errorCode", async () => {
  743. const t = setup();
  744. t.fact({ kind: "tool.lifecycle", phase: "started", toolCallId: "agent", toolName: "Agent" });
  745. t.fact({
  746. kind: "subagent.lifecycle",
  747. phase: "spawned",
  748. agentId: "a1",
  749. childSessionId: "child",
  750. parentToolCallId: "agent",
  751. background: true,
  752. });
  753. t.fact({ kind: "tool.lifecycle", phase: "completed", toolCallId: "agent", toolName: "Agent" });
  754. t.fact({
  755. sessionId: "child",
  756. kind: "turn.terminal",
  757. status: "failed",
  758. errorCode: "MODEL_RATE_LIMITED",
  759. errorMessage: "429 quota",
  760. });
  761. const steps = await t.steps();
  762. const summary = steps.find((s) => s.tool_name === "Agent" && s.status === "fail");
  763. expect(summary).toMatchObject({ error_code: "model_rate_limited" });
  764. });
  765. it("后台子 agent 被用户停止时,Agent 汇总 step 记 user_interrupt 而不是 other", async () => {
  766. const t = setup();
  767. t.fact({ kind: "tool.lifecycle", phase: "started", toolCallId: "agent", toolName: "Agent" });
  768. t.fact({
  769. kind: "subagent.lifecycle",
  770. phase: "spawned",
  771. agentId: "a1",
  772. childSessionId: "child",
  773. parentToolCallId: "agent",
  774. background: true,
  775. });
  776. t.fact({ kind: "tool.lifecycle", phase: "completed", toolCallId: "agent", toolName: "Agent" });
  777. t.fact({
  778. sessionId: "child",
  779. kind: "turn.terminal",
  780. status: "interrupted",
  781. errorCode: "USER_INTERRUPT",
  782. });
  783. const steps = await t.steps();
  784. const summary = steps.find((s) => s.tool_name === "Agent" && s.status === "fail");
  785. expect(summary).toMatchObject({ error_code: "user_interrupt" });
  786. });
  787. });
  788. describe("Workflow run 结果 workflow_run_result", () => {
  789. const engines: ConversationTelemetryEngine[] = [];
  790. afterEach(() => {
  791. for (const engine of engines.splice(0)) engine.dispose();
  792. resetMessageTelemetryForTest();
  793. });
  794. const base = { sessionId: "s", sourceCommandId: "launch-1", runId: "dwfrun-1", actorCount: 2 };
  795. it("终态与停止原因按白名单归一;非 stopped 时 stop_reason 为空串", () => {
  796. const detail = (status?: string, stopReason?: string) =>
  797. buildWorkflowRunResultTelemetryEvent({ ...base, status, stopReason }).eventExtraDetail;
  798. expect(detail("completed")).toEqual({
  799. workflow_run_id: "dwfrun-1",
  800. status: "completed",
  801. stop_reason: "",
  802. actor_count: "2",
  803. });
  804. expect(detail("errored", "user")).toMatchObject({ status: "errored", stop_reason: "" });
  805. for (const reason of WORKFLOW_RUN_STOP_REASONS) {
  806. expect(detail("stopped", reason)).toMatchObject({ status: "stopped", stop_reason: reason });
  807. }
  808. // stopped 却缺原因(CLI 丢掉了不认识的引擎原因)或原因不在白名单:other。
  809. expect(detail("stopped")).toMatchObject({ stop_reason: "other" });
  810. expect(detail("stopped", "quota /home/u")).toMatchObject({ stop_reason: "other" });
  811. expect(detail("weird")).toMatchObject({ status: "other", stop_reason: "" });
  812. expect(detail(undefined)).toMatchObject({ status: "other" });
  813. });
  814. it("事件属性:父会话、发起轮;不合规 run id 与计数不透传", () => {
  815. const event = buildWorkflowRunResultTelemetryEvent({ ...base, status: "completed" });
  816. expect(event).toMatchObject({
  817. elementName: "workflow_run_result",
  818. eventRegion: "app",
  819. eventType: "result",
  820. talkId: "s",
  821. messageId: "launch-1",
  822. });
  823. const odd = buildWorkflowRunResultTelemetryEvent({
  824. sessionId: "s",
  825. sourceCommandId: "",
  826. runId: "run /Users/me/secret",
  827. status: "completed",
  828. actorCount: Number.NaN,
  829. });
  830. expect(odd).not.toHaveProperty("messageId");
  831. expect(odd.eventExtraDetail).toMatchObject({ workflow_run_id: "", actor_count: "0" });
  832. expect(
  833. buildWorkflowRunResultTelemetryEvent({ ...base, actorCount: 3.7 }).eventExtraDetail
  834. .actor_count,
  835. ).toBe("3");
  836. expect(
  837. buildWorkflowRunResultTelemetryEvent({ ...base, actorCount: -1 }).eventExtraDetail
  838. .actor_count,
  839. ).toBe("0");
  840. });
  841. it("白名单与 fact schema、CLI 派生器、dwf 引擎的 RunStatus / RunStopReason 同步", () => {
  842. const read = (path: string) =>
  843. readFileSync(new URL(`../../../${path}`, import.meta.url), "utf8");
  844. const literals = (text: string) => [...text.matchAll(/"([a-z]+)"/gu)].map((m) => m[1]!).sort();
  845. const reasons = [...WORKFLOW_RUN_STOP_REASONS].sort();
  846. const statuses = [...WORKFLOW_RUN_RESULT_STATUSES].sort();
  847. const schema = read("packages/shared/src/zcode-protocol-v4/telemetry.ts");
  848. const schemaBlock =
  849. /const workflowLifecycleFactSchema = z([\s\S]*?)\.strict\(\);/u.exec(schema)?.[1] ?? "";
  850. expect(literals(/stopReason: z\.enum\(\[([^\]]*)\]\)/u.exec(schemaBlock)?.[1] ?? "")).toEqual(
  851. reasons,
  852. );
  853. expect(literals(/status: z\.enum\(\[([^\]]*)\]\)/u.exec(schemaBlock)?.[1] ?? "")).toEqual(
  854. statuses,
  855. );
  856. const cli = read(
  857. "apps/zcode-cli/packages/bootstrap/src/zcode-protocol-v4/conversation-telemetry-workflow-facts.ts",
  858. );
  859. expect(literals(/type WorkflowRunStopReason = ([^;]*);/u.exec(cli)?.[1] ?? "")).toEqual(
  860. reasons,
  861. );
  862. expect(literals(/type WorkflowRunSettledStatus = ([^;]*);/u.exec(cli)?.[1] ?? "")).toEqual(
  863. statuses,
  864. );
  865. const engineTypes = read("apps/zcode-cli/packages/dynamic-workflow/src/engine/types.ts");
  866. expect(literals(/export type RunStopReason = ([^;]*);/u.exec(engineTypes)?.[1] ?? "")).toEqual(
  867. reasons,
  868. );
  869. // RunStatus 另含 pending / running 两个非终态。
  870. expect(literals(/export type RunStatus = ([^;]*);/u.exec(engineTypes)?.[1] ?? "")).toEqual(
  871. [...statuses, "pending", "running"].sort(),
  872. );
  873. });
  874. function setup() {
  875. const reports: Array<{
  876. elementName: string;
  877. eventExtraDetail: Record<string, string>;
  878. talkId?: string;
  879. messageId?: string;
  880. }> = [];
  881. let seq = 0;
  882. const engine = new ConversationTelemetryEngine({
  883. workspaceScopeKey: "test",
  884. now: () => 100 + seq,
  885. platform: { reportTelemetryEvent: async () => {}, reportArmsCustomEvent: async () => {} },
  886. reportEvent: async (report) => {
  887. reports.push(report);
  888. },
  889. });
  890. engines.push(engine);
  891. const fact = (fields: Record<string, unknown>) =>
  892. engine.handleFact({
  893. version: 1,
  894. sessionId: "parent",
  895. sourceCommandId: "launch-1",
  896. eventId: `e${++seq}`,
  897. eventSeq: seq,
  898. occurredAt: 100 + seq,
  899. kind: "workflow.lifecycle",
  900. runId: "dwfrun-1",
  901. ...fields,
  902. } as ConversationTelemetryInput);
  903. const spawn = (agentId: string, childSessionId: string) =>
  904. fact({ phase: "actor-spawned", agentId, childSessionId, toolCallId: "create" });
  905. const settle = (fields: Record<string, unknown>) => fact({ phase: "run-settled", ...fields });
  906. const results = async () => {
  907. await engine.flushReportsForTest();
  908. return reports.filter((r) => r.elementName === "workflow_run_result");
  909. };
  910. return { fact, spawn, settle, results, reports, engine };
  911. }
  912. it("没有子 agent 的 run 也上报;错误原文不出本机", async () => {
  913. const t = setup();
  914. t.settle({ status: "errored", errorMessage: "SyntaxError at /home/u/flow.ts:3" });
  915. const results = await t.results();
  916. expect(results).toHaveLength(1);
  917. expect(results[0]).toMatchObject({
  918. talkId: "parent",
  919. messageId: "launch-1",
  920. eventExtraDetail: {
  921. workflow_run_id: "dwfrun-1",
  922. status: "errored",
  923. stop_reason: "",
  924. actor_count: "0",
  925. },
  926. });
  927. expect(JSON.stringify(t.reports)).not.toContain("SyntaxError");
  928. expect(JSON.stringify(t.reports)).not.toContain("/home/u");
  929. });
  930. it("有子 agent 的 run:计数按 agentId 去重,原有子 agent 汇总 step 照旧", async () => {
  931. const t = setup();
  932. t.spawn("site@0", "child-a");
  933. t.spawn("site@1", "child-b");
  934. // 同一子 agent 的 actor-created 重发(resume)不重复计数。
  935. t.spawn("site@0", "child-a");
  936. t.settle({
  937. status: "stopped",
  938. stopReason: "user",
  939. errorMessage: "Workflow run stopped (user)",
  940. });
  941. const results = await t.results();
  942. expect(results.map((r) => r.eventExtraDetail)).toEqual([
  943. { workflow_run_id: "dwfrun-1", status: "stopped", stop_reason: "user", actor_count: "2" },
  944. ]);
  945. const summaries = t.reports.filter(
  946. (r) =>
  947. r.elementName === "agent_step" &&
  948. r.eventExtraDetail.tool_call_id?.startsWith("tool_workflow_"),
  949. );
  950. expect(summaries).toHaveLength(2);
  951. for (const step of summaries) {
  952. expect(step.eventExtraDetail).toMatchObject({ status: "fail", workflow_run_id: "dwfrun-1" });
  953. }
  954. });
  955. it("同一 runId 每次结算都报(停下后恢复再跑完),计数跨结算累计;同一 fact 重投不重复", async () => {
  956. const t = setup();
  957. t.spawn("site@0", "child-a");
  958. t.settle({ status: "stopped", stopReason: "provider" });
  959. // 恢复后同一个 run:做完的子 agent 不一定重发 actor-created,新派的子 agent 照常登记。
  960. t.spawn("site@1", "child-b");
  961. t.fact({ eventId: "settle-2", phase: "run-settled", status: "completed" });
  962. t.fact({ eventId: "settle-2", phase: "run-settled", status: "completed" });
  963. const results = await t.results();
  964. expect(results.map((r) => r.eventExtraDetail)).toEqual([
  965. { workflow_run_id: "dwfrun-1", status: "stopped", stop_reason: "provider", actor_count: "1" },
  966. { workflow_run_id: "dwfrun-1", status: "completed", stop_reason: "", actor_count: "2" },
  967. ]);
  968. expect(results.every((r) => r.messageId === "launch-1")).toBe(true);
  969. });
  970. it("修订:旧 run 记 superseded,新 run 另起 runId、沿用发起轮", async () => {
  971. const t = setup();
  972. t.spawn("site@0", "child-a");
  973. t.settle({ status: "stopped", stopReason: "superseded" });
  974. t.fact({ runId: "dwfrun-2", phase: "actor-spawned", agentId: "site@0", childSessionId: "c2" });
  975. t.fact({ runId: "dwfrun-2", phase: "run-settled", status: "completed" });
  976. const results = await t.results();
  977. expect(results.map((r) => [r.messageId, r.eventExtraDetail])).toEqual([
  978. [
  979. "launch-1",
  980. {
  981. workflow_run_id: "dwfrun-1",
  982. status: "stopped",
  983. stop_reason: "superseded",
  984. actor_count: "1",
  985. },
  986. ],
  987. [
  988. "launch-1",
  989. { workflow_run_id: "dwfrun-2", status: "completed", stop_reason: "", actor_count: "1" },
  990. ],
  991. ]);
  992. });
  993. });