messageTelemetry.test.ts 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346
  1. import { afterEach, describe, expect, it } from "vitest";
  2. import {
  3. buildCustomSupplierKey,
  4. buildGhostSupplierKey,
  5. encodeCustomModelValue,
  6. type ZCodePersistedFileChange,
  7. } from "@zcode/shared";
  8. import {
  9. activatePromptTelemetry,
  10. buildCompactionTelemetryExtraDetail,
  11. buildPromptTelemetryExtraDetail,
  12. finalizePromptTelemetry,
  13. queuePromptTelemetry,
  14. recordAgentStepTelemetryEvent,
  15. recordSubagentToolAttribution,
  16. recordPromptModelRequestStarted,
  17. recordComposerFocus,
  18. recordComposerTextChange,
  19. recordPromptFirstToken,
  20. recordPromptPermissionRequest,
  21. recordPromptPermissionResponse,
  22. recordPromptTokenUsageDelta,
  23. rekeyQueuedPromptTelemetry,
  24. resetMessageTelemetryForTest,
  25. } from "../src/lib/messageTelemetry.js";
  26. afterEach(() => {
  27. resetMessageTelemetryForTest();
  28. });
  29. describe("messageTelemetry", () => {
  30. it("captures send button input timing from focus and first character", () => {
  31. recordComposerFocus("/tmp/workspace-a", 100);
  32. recordComposerTextChange("/tmp/workspace-a", "h", 120);
  33. expect(
  34. queuePromptTelemetry({
  35. workspacePath: "/tmp/workspace-a",
  36. taskId: "task-a",
  37. messageId: "message-a",
  38. sendTime: 200,
  39. }),
  40. ).toEqual({
  41. input_start_time: "100",
  42. input_first_char_time: "120",
  43. input_send_time: "200",
  44. });
  45. });
  46. it("builds message completion metrics from the active prompt lifecycle", () => {
  47. const fileChanges: ZCodePersistedFileChange[] = [
  48. {
  49. turnIndex: 0,
  50. snapshots: [
  51. {
  52. path: "src/example.ts",
  53. beforeContent: null,
  54. afterContent: "const a = 1;\nconst b = 2;\n",
  55. writeCount: 1,
  56. },
  57. ],
  58. },
  59. ];
  60. queuePromptTelemetry({
  61. workspacePath: "/tmp/workspace-a",
  62. taskId: "task-a",
  63. messageId: "message-a",
  64. sendTime: 200,
  65. extraDetail: {
  66. ask_mode: "plan",
  67. model_name: "claude-sonnet-4-5",
  68. model_provider: "provider-a",
  69. agent: "claude",
  70. },
  71. });
  72. activatePromptTelemetry("task-a", "message-a");
  73. recordPromptFirstToken("task-a", 260);
  74. recordPromptPermissionRequest({
  75. taskId: "task-a",
  76. requestId: "permission-a",
  77. toolCallId: "tool-a",
  78. now: 300,
  79. });
  80. recordPromptPermissionResponse({
  81. taskId: "task-a",
  82. requestId: "permission-a",
  83. now: 450,
  84. });
  85. recordAgentStepTelemetryEvent({
  86. taskId: "task-a",
  87. event: {
  88. type: "agent_message_chunk",
  89. taskId: "task-a",
  90. traceId: "trace-a",
  91. content: "done",
  92. },
  93. now: 500,
  94. });
  95. recordAgentStepTelemetryEvent({
  96. taskId: "task-a",
  97. event: {
  98. type: "task_complete",
  99. taskId: "task-a",
  100. traceId: "trace-a",
  101. stopReason: "stop",
  102. },
  103. now: 700,
  104. });
  105. expect(
  106. finalizePromptTelemetry({
  107. taskId: "task-a",
  108. status: "success",
  109. finishedAt: 700,
  110. fileChanges,
  111. usage: {
  112. inputTokens: 10,
  113. outputTokens: 20,
  114. totalTokens: 38,
  115. reasoningTokens: 5,
  116. cachedInputTokens: 2,
  117. cachedWriteInputTokens: 1,
  118. },
  119. }),
  120. ).toEqual({
  121. taskId: "task-a",
  122. messageId: "message-a",
  123. eventExtraDetail: {
  124. ask_mode: "plan",
  125. model_name: "claude-sonnet-4-5",
  126. model_provider: "provider-a",
  127. agent: "claude",
  128. input_tokens: "10",
  129. output_tokens: "20",
  130. reasoning_tokens: "5",
  131. cached_input_tokens: "2",
  132. cache_write_input_tokens: "1",
  133. tool_use_prompt_tokens: "0",
  134. total_tokens: "38",
  135. duration_ms: "500",
  136. waiting_ms: "150",
  137. generated_code_lines: "2",
  138. file_change_cnt: "1",
  139. time_to_first_token: "60",
  140. request_time: "200",
  141. status: "success",
  142. agent_composition: "main_only",
  143. agent_step_cnt: "1",
  144. retry_cnt: "0",
  145. tool_call_total: "0",
  146. tool_call_failed: "0",
  147. error_type: "",
  148. error_msg: "",
  149. },
  150. });
  151. });
  152. it("scopes completion step counts and loop indexes to the active prompt", () => {
  153. const runGenerationPrompt = (messageId: string, sendTime: number, finishedAt: number) => {
  154. queuePromptTelemetry({
  155. workspacePath: "/tmp/workspace-message-scope",
  156. taskId: "task-message-scope",
  157. messageId,
  158. sendTime,
  159. });
  160. activatePromptTelemetry("task-message-scope", messageId);
  161. recordAgentStepTelemetryEvent({
  162. taskId: "task-message-scope",
  163. event: {
  164. type: "agent_message_chunk",
  165. taskId: "task-message-scope",
  166. traceId: `trace-${messageId}`,
  167. content: "done",
  168. },
  169. now: sendTime + 10,
  170. });
  171. const [step] = recordAgentStepTelemetryEvent({
  172. taskId: "task-message-scope",
  173. event: {
  174. type: "task_complete",
  175. taskId: "task-message-scope",
  176. traceId: `trace-${messageId}`,
  177. stopReason: "stop",
  178. },
  179. now: finishedAt,
  180. });
  181. const completion = finalizePromptTelemetry({
  182. taskId: "task-message-scope",
  183. status: "success",
  184. finishedAt,
  185. });
  186. return { completion, step };
  187. };
  188. const first = runGenerationPrompt("message-scope-1", 100, 200);
  189. const second = runGenerationPrompt("message-scope-2", 300, 400);
  190. expect(first.step?.eventExtraDetail.loop_index).toBe("1");
  191. expect(first.completion?.eventExtraDetail.agent_step_cnt).toBe("1");
  192. expect(second.step?.eventExtraDetail.loop_index).toBe("1");
  193. expect(second.completion?.eventExtraDetail.agent_step_cnt).toBe("1");
  194. });
  195. it("rejects stale input chunks and tools at the shared step aggregation entry", () => {
  196. const taskId = "task-stale-step-input";
  197. queuePromptTelemetry({
  198. workspacePath: "/tmp/workspace-stale-step-input",
  199. taskId,
  200. messageId: "message-current",
  201. inputId: "input-current",
  202. sendTime: 100,
  203. });
  204. activatePromptTelemetry(taskId, "message-current");
  205. const staleChunkSteps = recordAgentStepTelemetryEvent({
  206. taskId,
  207. activeInputId: "input-current",
  208. event: {
  209. type: "agent_message_chunk",
  210. taskId,
  211. traceId: "trace-session",
  212. inputId: "input-stale",
  213. content: "stale response",
  214. },
  215. now: 120,
  216. });
  217. const staleToolSteps = recordAgentStepTelemetryEvent({
  218. taskId,
  219. activeInputId: "input-current",
  220. event: {
  221. type: "tool_call_update",
  222. taskId,
  223. traceId: "trace-session",
  224. inputId: "input-stale",
  225. toolId: "tool-stale",
  226. kind: "Bash",
  227. status: "failed",
  228. error: "stale failure",
  229. },
  230. now: 130,
  231. });
  232. const currentTerminalSteps = recordAgentStepTelemetryEvent({
  233. taskId,
  234. activeInputId: "input-current",
  235. event: {
  236. type: "task_complete",
  237. taskId,
  238. traceId: "trace-session",
  239. inputId: "input-current",
  240. stopReason: "end_turn",
  241. },
  242. now: 150,
  243. });
  244. const completion = finalizePromptTelemetry({
  245. taskId,
  246. status: "success",
  247. finishedAt: 150,
  248. });
  249. expect(staleChunkSteps).toEqual([]);
  250. expect(staleToolSteps).toEqual([]);
  251. expect(currentTerminalSteps).toEqual([]);
  252. expect(completion?.eventExtraDetail).toMatchObject({
  253. time_to_first_token: "-1",
  254. agent_step_cnt: "0",
  255. tool_call_total: "0",
  256. tool_call_failed: "0",
  257. });
  258. });
  259. it("uses runtime activeInputId after a queued prompt rebinds its pending input", () => {
  260. const taskId = "task-queued-input-rebind";
  261. queuePromptTelemetry({
  262. workspacePath: "/tmp/workspace-queued-input-rebind",
  263. taskId,
  264. messageId: "message-queued",
  265. inputId: "input-pending",
  266. sendTime: 200,
  267. extraDetail: {
  268. model_name: "provider-old/model-old",
  269. model_provider: "provider-old",
  270. },
  271. });
  272. activatePromptTelemetry(taskId, "message-queued");
  273. const [toolStep] = recordAgentStepTelemetryEvent({
  274. taskId,
  275. activeInputId: "input-actual",
  276. event: {
  277. type: "tool_call_update",
  278. taskId,
  279. traceId: "trace-session",
  280. inputId: "input-actual",
  281. toolId: "tool-current",
  282. kind: "Read",
  283. status: "completed",
  284. },
  285. now: 220,
  286. });
  287. recordPromptModelRequestStarted(
  288. taskId,
  289. {
  290. type: "task_network_debug_status",
  291. taskId,
  292. traceId: "trace-session",
  293. inputId: "input-actual",
  294. eventKey: "event-actual",
  295. statusType: "model_request_started",
  296. providerId: "provider-actual",
  297. modelId: "model-actual",
  298. requestHeaders: {},
  299. responseHeaders: {},
  300. requestHeaderCount: 0,
  301. responseHeaderCount: 0,
  302. },
  303. "input-actual",
  304. );
  305. const completion = finalizePromptTelemetry({
  306. taskId,
  307. status: "success",
  308. finishedAt: 240,
  309. });
  310. expect(toolStep?.eventExtraDetail).toMatchObject({
  311. loop_index: "1",
  312. tool_call_id: "tool-current",
  313. status: "success",
  314. });
  315. expect(completion?.eventExtraDetail).toMatchObject({
  316. agent_step_cnt: "1",
  317. tool_call_total: "1",
  318. tool_call_failed: "0",
  319. model_name: "provider-actual/model-actual",
  320. model_provider: "provider-actual",
  321. });
  322. });
  323. it("derives tool completion counts from finalized steps in the active prompt", () => {
  324. queuePromptTelemetry({
  325. workspacePath: "/tmp/workspace-tool-count",
  326. taskId: "task-tool-count",
  327. messageId: "message-tool-count",
  328. sendTime: 100,
  329. });
  330. activatePromptTelemetry("task-tool-count", "message-tool-count");
  331. for (const [toolId, status, error] of [
  332. ["tool-ok", "completed", undefined],
  333. ["tool-failed", "failed", "command timed out"],
  334. ] as const) {
  335. recordAgentStepTelemetryEvent({
  336. taskId: "task-tool-count",
  337. event: {
  338. type: "tool_call",
  339. taskId: "task-tool-count",
  340. traceId: "trace-tool-count",
  341. toolId,
  342. kind: "bash",
  343. toolName: "bash",
  344. title: "Run command",
  345. input: {},
  346. raw: {},
  347. },
  348. now: 120,
  349. });
  350. recordAgentStepTelemetryEvent({
  351. taskId: "task-tool-count",
  352. event: {
  353. type: "tool_call_update",
  354. taskId: "task-tool-count",
  355. traceId: "trace-tool-count",
  356. toolId,
  357. status,
  358. kind: "bash",
  359. toolName: "bash",
  360. ...(error ? { error } : {}),
  361. raw: {},
  362. },
  363. now: 150,
  364. });
  365. }
  366. const completion = finalizePromptTelemetry({
  367. taskId: "task-tool-count",
  368. status: "fail",
  369. finishedAt: 200,
  370. });
  371. expect(completion?.eventExtraDetail).toMatchObject({
  372. agent_step_cnt: "2",
  373. tool_call_total: "2",
  374. tool_call_failed: "1",
  375. error_type: "TOOL_CALL_FAILED",
  376. error_msg: "command timed out",
  377. });
  378. });
  379. it("does not append success-only token fields and reports failure details for failed prompts", () => {
  380. queuePromptTelemetry({
  381. workspacePath: "/tmp/workspace-b",
  382. taskId: "task-b",
  383. messageId: "message-b",
  384. sendTime: 100,
  385. extraDetail: {
  386. ask_mode: "default",
  387. model_name: "model-b",
  388. model_provider: "provider-b",
  389. agent: "codex",
  390. },
  391. });
  392. activatePromptTelemetry("task-b", "message-b");
  393. for (const [toolId, kind, status, error] of [
  394. ["tool-ok", "read", "completed", undefined],
  395. ["tool-failed", "bash", "failed", "command timed out"],
  396. ] as const) {
  397. recordAgentStepTelemetryEvent({
  398. taskId: "task-b",
  399. event: {
  400. type: "tool_call",
  401. taskId: "task-b",
  402. traceId: "trace-b",
  403. toolId,
  404. kind,
  405. input: {},
  406. raw: {},
  407. },
  408. now: 120,
  409. });
  410. recordAgentStepTelemetryEvent({
  411. taskId: "task-b",
  412. event: {
  413. type: "tool_call_update",
  414. taskId: "task-b",
  415. traceId: "trace-b",
  416. toolId,
  417. kind,
  418. status,
  419. ...(error ? { error } : {}),
  420. raw: {},
  421. },
  422. now: 150,
  423. });
  424. }
  425. expect(
  426. finalizePromptTelemetry({
  427. taskId: "task-b",
  428. status: "fail",
  429. finishedAt: 180,
  430. usage: {
  431. inputTokens: 1,
  432. outputTokens: 2,
  433. totalTokens: 3,
  434. },
  435. }),
  436. ).toEqual({
  437. taskId: "task-b",
  438. messageId: "message-b",
  439. eventExtraDetail: {
  440. ask_mode: "default",
  441. model_name: "model-b",
  442. model_provider: "provider-b",
  443. agent: "codex",
  444. duration_ms: "80",
  445. waiting_ms: "0",
  446. generated_code_lines: "0",
  447. file_change_cnt: "0",
  448. time_to_first_token: "20",
  449. request_time: "100",
  450. status: "fail",
  451. agent_composition: "main_only",
  452. agent_step_cnt: "2",
  453. retry_cnt: "0",
  454. tool_call_total: "2",
  455. tool_call_failed: "1",
  456. error_type: "TOOL_CALL_FAILED",
  457. error_msg: "command timed out",
  458. },
  459. });
  460. });
  461. it("reports accumulated token usage for failed prompts from usage delta events", () => {
  462. queuePromptTelemetry({
  463. workspacePath: "/tmp/workspace-fail-usage",
  464. taskId: "task-fail-usage",
  465. messageId: "message-fail-usage",
  466. sendTime: 100,
  467. extraDetail: {
  468. ask_mode: "build",
  469. },
  470. });
  471. activatePromptTelemetry("task-fail-usage", "message-fail-usage");
  472. recordPromptTokenUsageDelta({
  473. taskId: "task-fail-usage",
  474. eventKey: "usage-event-1",
  475. usage: {
  476. inputTokens: 10,
  477. outputTokens: 4,
  478. totalTokens: 17,
  479. reasoningTokens: 1,
  480. cachedInputTokens: 2,
  481. cachedWriteInputTokens: 1,
  482. },
  483. });
  484. recordPromptTokenUsageDelta({
  485. taskId: "task-fail-usage",
  486. eventKey: "usage-event-1",
  487. usage: {
  488. inputTokens: 999,
  489. outputTokens: 999,
  490. totalTokens: 999,
  491. },
  492. });
  493. recordPromptTokenUsageDelta({
  494. taskId: "task-fail-usage",
  495. eventKey: "usage-event-2",
  496. usage: {
  497. inputTokens: 3,
  498. outputTokens: 2,
  499. totalTokens: 5,
  500. },
  501. });
  502. expect(
  503. finalizePromptTelemetry({
  504. taskId: "task-fail-usage",
  505. status: "fail",
  506. finishedAt: 250,
  507. })?.eventExtraDetail,
  508. ).toEqual(
  509. expect.objectContaining({
  510. status: "fail",
  511. input_tokens: "13",
  512. output_tokens: "6",
  513. reasoning_tokens: "1",
  514. cached_input_tokens: "2",
  515. cache_write_input_tokens: "1",
  516. tool_use_prompt_tokens: "0",
  517. total_tokens: "22",
  518. token_source: "usage_delta",
  519. }),
  520. );
  521. });
  522. it("reports terminal error details for failed prompts", () => {
  523. queuePromptTelemetry({
  524. workspacePath: "/tmp/workspace-terminal-error",
  525. taskId: "task-terminal-error",
  526. messageId: "message-terminal-error",
  527. sendTime: 100,
  528. });
  529. activatePromptTelemetry("task-terminal-error", "message-terminal-error");
  530. expect(
  531. finalizePromptTelemetry({
  532. taskId: "task-terminal-error",
  533. status: "fail",
  534. finishedAt: 180,
  535. errorType: "MODEL_REQUEST_FAILED",
  536. errorMsg: "method not allowed",
  537. })?.eventExtraDetail,
  538. ).toEqual(
  539. expect.objectContaining({
  540. status: "fail",
  541. error_type: "MODEL_REQUEST_FAILED",
  542. error_msg: "method not allowed",
  543. }),
  544. );
  545. });
  546. it("reports accumulated token usage for interrupted prompts from usage delta events", () => {
  547. queuePromptTelemetry({
  548. workspacePath: "/tmp/workspace-interrupt-usage",
  549. taskId: "task-interrupt-usage",
  550. messageId: "message-interrupt-usage",
  551. sendTime: 100,
  552. });
  553. activatePromptTelemetry("task-interrupt-usage", "message-interrupt-usage");
  554. recordPromptTokenUsageDelta({
  555. taskId: "task-interrupt-usage",
  556. eventKey: "usage-event-interrupt",
  557. usage: {
  558. inputTokens: 8,
  559. outputTokens: 1,
  560. totalTokens: 11,
  561. cachedInputTokens: 2,
  562. },
  563. });
  564. expect(
  565. finalizePromptTelemetry({
  566. taskId: "task-interrupt-usage",
  567. status: "user_interrupt",
  568. finishedAt: 180,
  569. })?.eventExtraDetail,
  570. ).toEqual(
  571. expect.objectContaining({
  572. status: "user_interrupt",
  573. input_tokens: "8",
  574. output_tokens: "1",
  575. reasoning_tokens: "0",
  576. cached_input_tokens: "2",
  577. cache_write_input_tokens: "0",
  578. total_tokens: "11",
  579. token_source: "usage_delta",
  580. }),
  581. );
  582. });
  583. it("keeps queued prompt telemetry when the queued message id is replaced by service ack", () => {
  584. queuePromptTelemetry({
  585. workspacePath: "/tmp/workspace-queued-rekey",
  586. taskId: "task-queued-rekey",
  587. messageId: "local-queued-id",
  588. sendTime: 100,
  589. extraDetail: {
  590. ask_mode: "build",
  591. },
  592. });
  593. rekeyQueuedPromptTelemetry("task-queued-rekey", "local-queued-id", "ack-queued-id");
  594. activatePromptTelemetry("task-queued-rekey", "ack-queued-id");
  595. expect(
  596. finalizePromptTelemetry({
  597. taskId: "task-queued-rekey",
  598. status: "fail",
  599. finishedAt: 250,
  600. }),
  601. ).toEqual({
  602. taskId: "task-queued-rekey",
  603. messageId: "ack-queued-id",
  604. eventExtraDetail: {
  605. ask_mode: "build",
  606. duration_ms: "150",
  607. waiting_ms: "0",
  608. generated_code_lines: "0",
  609. file_change_cnt: "0",
  610. time_to_first_token: "-1",
  611. request_time: "100",
  612. status: "fail",
  613. agent_composition: "main_only",
  614. agent_step_cnt: "0",
  615. retry_cnt: "0",
  616. tool_call_total: "0",
  617. tool_call_failed: "0",
  618. error_type: "UNKNOWN",
  619. error_msg: "",
  620. },
  621. });
  622. });
  623. it("resolves model_provider from native custom and ghost supplier keys", () => {
  624. expect(
  625. buildPromptTelemetryExtraDetail({
  626. askMode: "plan",
  627. modelName: "model-native",
  628. provider: "claude",
  629. selectedSupplierKey: "native:claude",
  630. }),
  631. ).toEqual({
  632. ask_mode: "plan",
  633. model_name: "model-native",
  634. model_provider: "claude",
  635. agent: "claude",
  636. plan_status: "unknown",
  637. plan_product_id: "",
  638. });
  639. expect(
  640. buildPromptTelemetryExtraDetail({
  641. askMode: "plan",
  642. modelName: "model-custom",
  643. provider: "claude",
  644. selectedSupplierKey: buildCustomSupplierKey("provider-a"),
  645. }),
  646. ).toEqual({
  647. ask_mode: "plan",
  648. model_name: "model-custom",
  649. model_provider: "provider-a",
  650. agent: "claude",
  651. plan_status: "unknown",
  652. plan_product_id: "",
  653. });
  654. expect(
  655. buildPromptTelemetryExtraDetail({
  656. askMode: "plan",
  657. modelName: "model-ghost",
  658. provider: "gemini",
  659. selectedSupplierKey: buildGhostSupplierKey("gemini", "mismatch", "https://demo.invalid"),
  660. }),
  661. ).toEqual({
  662. ask_mode: "plan",
  663. model_name: "model-ghost",
  664. model_provider: "gemini",
  665. agent: "gemini",
  666. plan_status: "unknown",
  667. plan_product_id: "",
  668. });
  669. });
  670. it("freezes plan identity fields from send button into message completion", () => {
  671. const sendButtonExtra = queuePromptTelemetry({
  672. workspacePath: "/tmp/workspace-a",
  673. taskId: "task-a",
  674. messageId: "message-a",
  675. sendTime: 200,
  676. extraDetail: buildPromptTelemetryExtraDetail({
  677. askMode: "chat",
  678. modelName: "glm-5.1",
  679. provider: "glm",
  680. providerBaseURL: "https://api.z.ai/api/paas/v4",
  681. planIdentitySnapshot: {
  682. generatedAt: 100,
  683. planStatus: "coding_plan",
  684. planProductId: "product-coding-pro",
  685. },
  686. }),
  687. });
  688. activatePromptTelemetry("task-a", "message-a");
  689. const completion = finalizePromptTelemetry({
  690. taskId: "task-a",
  691. status: "success",
  692. finishedAt: 300,
  693. taskMessages: [],
  694. fileChanges: [],
  695. });
  696. expect(sendButtonExtra).toMatchObject({
  697. plan_status: "coding_plan",
  698. plan_product_id: "product-coding-pro",
  699. provider_name: "api.z.ai",
  700. });
  701. expect(completion?.eventExtraDetail).toMatchObject({
  702. plan_status: "coding_plan",
  703. plan_product_id: "product-coding-pro",
  704. provider_name: "api.z.ai",
  705. });
  706. });
  707. it("prefers provider-qualified UI model value over stale supplier key for send button", () => {
  708. expect(
  709. buildPromptTelemetryExtraDetail({
  710. askMode: "plan",
  711. modelName: "4209ad4c-6650-4928-b44e-1167f913289a/deepseek-v4-flash",
  712. provider: "glm",
  713. selectedSupplierKey: "native:glm",
  714. }),
  715. ).toEqual({
  716. ask_mode: "plan",
  717. model_name: "4209ad4c-6650-4928-b44e-1167f913289a/deepseek-v4-flash",
  718. model_provider: "4209ad4c-6650-4928-b44e-1167f913289a",
  719. agent: "glm",
  720. plan_status: "unknown",
  721. plan_product_id: "",
  722. });
  723. expect(
  724. buildPromptTelemetryExtraDetail({
  725. askMode: "plan",
  726. modelName: encodeCustomModelValue("provider-custom", "deepseek-v4-flash"),
  727. provider: "glm",
  728. selectedSupplierKey: "native:glm",
  729. }),
  730. ).toEqual({
  731. ask_mode: "plan",
  732. model_name: encodeCustomModelValue("provider-custom", "deepseek-v4-flash"),
  733. model_provider: "provider-custom",
  734. agent: "glm",
  735. plan_status: "unknown",
  736. plan_product_id: "",
  737. });
  738. });
  739. it("keeps send button model from UI snapshot but completes with actual model request", () => {
  740. expect(
  741. queuePromptTelemetry({
  742. workspacePath: "/tmp/workspace-actual",
  743. taskId: "task-actual",
  744. messageId: "message-actual",
  745. inputId: "input-actual",
  746. sendTime: 100,
  747. extraDetail: {
  748. ask_mode: "build",
  749. model_name: "account:bigmodel-start-plan/GLM-5.2",
  750. model_provider: "provider-custom",
  751. agent: "glm",
  752. },
  753. }),
  754. ).toMatchObject({
  755. model_name: "account:bigmodel-start-plan/GLM-5.2",
  756. model_provider: "provider-custom",
  757. });
  758. activatePromptTelemetry("task-actual", "message-actual");
  759. recordPromptModelRequestStarted("task-actual", {
  760. type: "task_network_debug_status",
  761. taskId: "task-actual",
  762. traceId: "trace-actual",
  763. inputId: "input-actual",
  764. eventKey: "event-actual",
  765. statusType: "model_request_started",
  766. providerId: "provider-custom",
  767. modelId: "GLM-5.2",
  768. requestHeaders: {},
  769. responseHeaders: {},
  770. requestHeaderCount: 0,
  771. responseHeaderCount: 0,
  772. });
  773. expect(
  774. finalizePromptTelemetry({
  775. taskId: "task-actual",
  776. status: "success",
  777. finishedAt: 180,
  778. })?.eventExtraDetail,
  779. ).toMatchObject({
  780. model_name: "provider-custom/GLM-5.2",
  781. model_provider: "provider-custom",
  782. });
  783. });
  784. it("adds provider hostname from provider endpoint and prefers runtime baseURL", () => {
  785. expect(
  786. buildPromptTelemetryExtraDetail({
  787. askMode: "build",
  788. modelName: encodeCustomModelValue("provider-custom", "glm-5.2"),
  789. provider: "glm",
  790. selectedSupplierKey: buildCustomSupplierKey("provider-custom"),
  791. providerBaseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
  792. }),
  793. ).toMatchObject({
  794. model_provider: "provider-custom",
  795. provider_name: "dashscope.aliyuncs.com",
  796. });
  797. queuePromptTelemetry({
  798. workspacePath: "/tmp/workspace-hostname",
  799. taskId: "task-hostname",
  800. messageId: "message-hostname",
  801. inputId: "input-hostname",
  802. sendTime: 100,
  803. extraDetail: {
  804. model_name: encodeCustomModelValue("provider-custom", "glm-5.2"),
  805. model_provider: "provider-custom",
  806. provider_name: "dashscope.aliyuncs.com",
  807. },
  808. });
  809. activatePromptTelemetry("task-hostname", "message-hostname");
  810. recordPromptModelRequestStarted("task-hostname", {
  811. type: "task_network_debug_status",
  812. taskId: "task-hostname",
  813. traceId: "trace-hostname",
  814. inputId: "input-hostname",
  815. eventKey: "event-hostname",
  816. statusType: "model_request_started",
  817. providerId: "provider-custom",
  818. modelId: "glm-5.2",
  819. baseURL: "https://runtime.example.com/v1/chat/completions",
  820. requestHeaders: {},
  821. responseHeaders: {},
  822. requestHeaderCount: 0,
  823. responseHeaderCount: 0,
  824. });
  825. expect(
  826. finalizePromptTelemetry({
  827. taskId: "task-hostname",
  828. status: "success",
  829. finishedAt: 180,
  830. })?.eventExtraDetail,
  831. ).toMatchObject({
  832. model_provider: "provider-custom",
  833. provider_name: "runtime.example.com",
  834. });
  835. });
  836. it("ignores model request telemetry for a different prompt input", () => {
  837. queuePromptTelemetry({
  838. workspacePath: "/tmp/workspace-input",
  839. taskId: "task-input",
  840. messageId: "message-input",
  841. inputId: "input-current",
  842. sendTime: 100,
  843. extraDetail: {
  844. model_name: "account:bigmodel-start-plan/GLM-5.2",
  845. model_provider: "provider-custom",
  846. },
  847. });
  848. activatePromptTelemetry("task-input", "message-input");
  849. recordPromptModelRequestStarted("task-input", {
  850. type: "task_network_debug_status",
  851. taskId: "task-input",
  852. traceId: "trace-input",
  853. inputId: "input-other",
  854. eventKey: "event-input",
  855. statusType: "model_request_started",
  856. providerId: "provider-custom",
  857. modelId: "GLM-5.2",
  858. requestHeaders: {},
  859. responseHeaders: {},
  860. requestHeaderCount: 0,
  861. responseHeaderCount: 0,
  862. });
  863. expect(
  864. finalizePromptTelemetry({
  865. taskId: "task-input",
  866. status: "success",
  867. finishedAt: 180,
  868. })?.eventExtraDetail,
  869. ).toMatchObject({
  870. model_name: "builtin:bigmodel-start-plan/GLM-5.2",
  871. model_provider: "provider-custom",
  872. });
  873. });
  874. it("builds compaction telemetry for terminal statuses with provider/model and token metrics", () => {
  875. const detail = buildCompactionTelemetryExtraDetail({
  876. timeline: {
  877. version: 1,
  878. kind: "synthetic",
  879. type: "context_compaction",
  880. operationId: "op-1",
  881. status: "completed",
  882. trigger: "auto",
  883. display: "separator",
  884. reason: "context_limit",
  885. attempt: 2,
  886. startedAt: 1000,
  887. endedAt: 1500,
  888. preCompactTokenCount: 20000,
  889. postCompactTokenCount: 5000,
  890. truePostCompactTokenCount: 5200,
  891. },
  892. provider: "claude",
  893. modelName: "model-x",
  894. selectedSupplierKey: "native:claude",
  895. });
  896. expect(detail).toEqual({
  897. status: "completed",
  898. trigger: "auto",
  899. reason: "context_limit",
  900. attempt: "2",
  901. duration_ms: "500",
  902. pre_compact_tokens: "20000",
  903. post_compact_tokens: "5000",
  904. true_post_compact_tokens: "5200",
  905. compact_ratio: "0.2500",
  906. model_name: "model-x",
  907. model_provider: "claude",
  908. });
  909. });
  910. it("leaves compact_ratio and duration empty when token/timing data is missing", () => {
  911. const detail = buildCompactionTelemetryExtraDetail({
  912. timeline: {
  913. version: 1,
  914. kind: "synthetic",
  915. type: "context_compaction",
  916. operationId: "op-2",
  917. status: "failed",
  918. trigger: "manual",
  919. display: "separator",
  920. },
  921. provider: "gemini",
  922. });
  923. expect(detail).toMatchObject({
  924. status: "failed",
  925. trigger: "manual",
  926. reason: "",
  927. attempt: "0",
  928. duration_ms: "",
  929. pre_compact_tokens: "0",
  930. post_compact_tokens: "0",
  931. true_post_compact_tokens: "0",
  932. compact_ratio: "",
  933. model_name: "",
  934. model_provider: "gemini",
  935. });
  936. });
  937. it("returns null for non-terminal compaction statuses", () => {
  938. for (const status of ["started", "retrying", "skipped"] as const) {
  939. expect(
  940. buildCompactionTelemetryExtraDetail({
  941. timeline: {
  942. version: 1,
  943. kind: "synthetic",
  944. type: "context_compaction",
  945. operationId: `op-${status}`,
  946. status,
  947. trigger: "auto",
  948. display: "separator",
  949. },
  950. provider: "claude",
  951. }),
  952. ).toBeNull();
  953. }
  954. });
  955. it("emits agent_step events for reasoning, tool calls, and generation", () => {
  956. queuePromptTelemetry({
  957. workspacePath: "/tmp/workspace-c",
  958. taskId: "task-c",
  959. messageId: "message-c",
  960. sendTime: 100,
  961. extraDetail: {
  962. model_name: "claude-sonnet-4-5",
  963. model_provider: "anthropic",
  964. provider_name: "api.anthropic.com",
  965. },
  966. });
  967. activatePromptTelemetry("task-c", "message-c");
  968. expect(
  969. recordAgentStepTelemetryEvent({
  970. taskId: "task-c",
  971. event: {
  972. type: "agent_thought_chunk",
  973. taskId: "task-c",
  974. traceId: "trace-c",
  975. content: "thinking",
  976. },
  977. now: 110,
  978. }),
  979. ).toEqual([]);
  980. expect(
  981. recordAgentStepTelemetryEvent({
  982. taskId: "task-c",
  983. event: {
  984. type: "tool_call",
  985. taskId: "task-c",
  986. traceId: "trace-c",
  987. toolId: "tool-c",
  988. kind: "read",
  989. toolName: "read_file",
  990. title: "Read file",
  991. input: {},
  992. raw: {},
  993. },
  994. now: 150,
  995. }),
  996. ).toEqual([
  997. {
  998. taskId: "task-c",
  999. messageId: "message-c",
  1000. eventExtraDetail: {
  1001. step_id: expect.any(String),
  1002. is_tftt_cached: "0",
  1003. loop_index: "1",
  1004. step_type: "reasoning",
  1005. model_name: "claude-sonnet-4-5",
  1006. model_provider: "anthropic",
  1007. provider_name: "api.anthropic.com",
  1008. model_request_id: "",
  1009. model_request_count: "0",
  1010. token_usage_scope: "",
  1011. is_tool_call: "0",
  1012. tool_name: "",
  1013. tool_call_id: "",
  1014. duration_ms: "40",
  1015. waiting_ms: "0",
  1016. generation_tail_finalize_ms: "",
  1017. status: "success",
  1018. input_tokens: "0",
  1019. output_tokens: "0",
  1020. reasoning_tokens: "0",
  1021. cached_tokens: "0",
  1022. cache_write_input_tokens: "0",
  1023. total_tokens: "0",
  1024. error_type: "",
  1025. error_msg: "",
  1026. },
  1027. },
  1028. ]);
  1029. expect(
  1030. recordAgentStepTelemetryEvent({
  1031. taskId: "task-c",
  1032. event: {
  1033. type: "tool_call_update",
  1034. taskId: "task-c",
  1035. traceId: "trace-c",
  1036. toolId: "tool-c",
  1037. status: "failed",
  1038. kind: "read",
  1039. toolName: "read_file",
  1040. error: "File not found: utils.ts",
  1041. raw: {},
  1042. },
  1043. now: 190,
  1044. }),
  1045. ).toEqual([
  1046. {
  1047. taskId: "task-c",
  1048. messageId: "message-c",
  1049. eventExtraDetail: {
  1050. step_id: expect.any(String),
  1051. is_tftt_cached: "0",
  1052. loop_index: "2",
  1053. step_type: "tool_call",
  1054. model_name: "claude-sonnet-4-5",
  1055. model_provider: "anthropic",
  1056. provider_name: "api.anthropic.com",
  1057. model_request_id: "",
  1058. model_request_count: "0",
  1059. token_usage_scope: "",
  1060. is_tool_call: "1",
  1061. tool_name: "read_file",
  1062. tool_call_id: "tool-c",
  1063. duration_ms: "40",
  1064. waiting_ms: "0",
  1065. generation_tail_finalize_ms: "",
  1066. status: "fail",
  1067. input_tokens: "0",
  1068. output_tokens: "0",
  1069. reasoning_tokens: "0",
  1070. cached_tokens: "0",
  1071. cache_write_input_tokens: "0",
  1072. total_tokens: "0",
  1073. error_type: "TOOL_EXEC_ERROR",
  1074. error_msg: "File not found: utils.ts",
  1075. },
  1076. },
  1077. ]);
  1078. expect(
  1079. recordAgentStepTelemetryEvent({
  1080. taskId: "task-c",
  1081. event: {
  1082. type: "agent_message_chunk",
  1083. taskId: "task-c",
  1084. traceId: "trace-c",
  1085. content: "done",
  1086. },
  1087. now: 200,
  1088. }),
  1089. ).toEqual([]);
  1090. expect(
  1091. recordAgentStepTelemetryEvent({
  1092. taskId: "task-c",
  1093. event: {
  1094. type: "task_complete",
  1095. taskId: "task-c",
  1096. traceId: "trace-c",
  1097. stopReason: "stop",
  1098. },
  1099. now: 260,
  1100. }),
  1101. ).toEqual([
  1102. {
  1103. taskId: "task-c",
  1104. messageId: "message-c",
  1105. eventExtraDetail: {
  1106. step_id: expect.any(String),
  1107. is_tftt_cached: "0",
  1108. loop_index: "3",
  1109. step_type: "generation",
  1110. model_name: "claude-sonnet-4-5",
  1111. model_provider: "anthropic",
  1112. provider_name: "api.anthropic.com",
  1113. model_request_id: "",
  1114. model_request_count: "0",
  1115. token_usage_scope: "",
  1116. is_tool_call: "0",
  1117. tool_name: "",
  1118. tool_call_id: "",
  1119. duration_ms: "60",
  1120. waiting_ms: "0",
  1121. generation_tail_finalize_ms: "60",
  1122. status: "success",
  1123. input_tokens: "0",
  1124. output_tokens: "0",
  1125. reasoning_tokens: "0",
  1126. cached_tokens: "0",
  1127. cache_write_input_tokens: "0",
  1128. total_tokens: "0",
  1129. error_type: "",
  1130. error_msg: "",
  1131. },
  1132. },
  1133. ]);
  1134. });
  1135. it("成功 CronCreate 的 agent_step 携带新生成的 automation_id", () => {
  1136. queuePromptTelemetry({
  1137. workspacePath: "/tmp/workspace-cron-create",
  1138. taskId: "task-cron-create",
  1139. messageId: "message-cron-create",
  1140. sendTime: 100,
  1141. });
  1142. activatePromptTelemetry("task-cron-create", "message-cron-create");
  1143. recordAgentStepTelemetryEvent({
  1144. taskId: "task-cron-create",
  1145. event: {
  1146. type: "tool_call",
  1147. taskId: "task-cron-create",
  1148. traceId: "trace-cron-create",
  1149. toolId: "tool-cron-create",
  1150. kind: "CronCreate",
  1151. toolName: "CronCreate",
  1152. title: "CronCreate",
  1153. input: {},
  1154. raw: {},
  1155. },
  1156. now: 110,
  1157. });
  1158. const [step] = recordAgentStepTelemetryEvent({
  1159. taskId: "task-cron-create",
  1160. event: {
  1161. type: "tool_call_update",
  1162. taskId: "task-cron-create",
  1163. traceId: "trace-cron-create",
  1164. toolId: "tool-cron-create",
  1165. status: "completed",
  1166. kind: "CronCreate",
  1167. toolName: "CronCreate",
  1168. content: JSON.stringify({ automation: { automationId: "automation-created" } }),
  1169. raw: {},
  1170. },
  1171. now: 130,
  1172. });
  1173. expect(step?.eventExtraDetail).toMatchObject({
  1174. tool_name: "CronCreate",
  1175. status: "success",
  1176. automation_id: "automation-created",
  1177. });
  1178. });
  1179. it.each([
  1180. ["failed", { skill: "missing-skill" }, "unknown"],
  1181. ["denied", { name: "legacy-skill" }, "unknown"],
  1182. ["stopped", { skill: "cancelled-skill" }, "unknown"],
  1183. ["failed", { skill: "/Users/FAKE_USER/private" }, "unknown"],
  1184. ["denied", { name: "https://example.com/?token=FAKE" }, "unknown"],
  1185. ["stopped", { skill: "demo\nFAKE_SECRET" }, "unknown"],
  1186. ["failed", { skill: "sk-" + "a".repeat(49) }, "unknown"],
  1187. ["stopped", { skill: "a".repeat(5000) }, "unknown"],
  1188. ["completed", {}, "unknown"],
  1189. ["failed", { skill: 123 }, "unknown"],
  1190. ] as const)("Skill %s 在无解析 metadata 时不保留请求原文", (status, input, expected) => {
  1191. queuePromptTelemetry({
  1192. workspacePath: "/tmp/skill",
  1193. taskId: "skill-name",
  1194. messageId: "message",
  1195. sendTime: 100,
  1196. });
  1197. activatePromptTelemetry("skill-name", "message");
  1198. recordAgentStepTelemetryEvent({
  1199. taskId: "skill-name",
  1200. now: 110,
  1201. event: {
  1202. type: "tool_call",
  1203. taskId: "skill-name",
  1204. traceId: "trace",
  1205. toolId: "tool",
  1206. kind: "Skill",
  1207. toolName: "Skill",
  1208. title: "",
  1209. input,
  1210. raw: {},
  1211. },
  1212. });
  1213. const [step] = recordAgentStepTelemetryEvent({
  1214. taskId: "skill-name",
  1215. now: 120,
  1216. event: {
  1217. type: "tool_call_update",
  1218. taskId: "skill-name",
  1219. traceId: "trace",
  1220. toolId: "tool",
  1221. kind: "Skill",
  1222. toolName: "Skill",
  1223. status,
  1224. raw: {},
  1225. },
  1226. });
  1227. expect(step?.eventExtraDetail.skill_name).toBe(expected);
  1228. expect(step?.eventExtraDetail).not.toHaveProperty("skill_plugin_id");
  1229. });
  1230. it("Skill tool step 携带解析后的 skill metadata,普通 tool step 不携带", () => {
  1231. queuePromptTelemetry({
  1232. workspacePath: "/tmp/workspace-skill",
  1233. taskId: "task-skill",
  1234. messageId: "message-skill",
  1235. sendTime: 100,
  1236. });
  1237. activatePromptTelemetry("task-skill", "message-skill");
  1238. recordAgentStepTelemetryEvent({
  1239. taskId: "task-skill",
  1240. event: {
  1241. type: "tool_call",
  1242. taskId: "task-skill",
  1243. traceId: "trace-skill",
  1244. toolId: "tool-skill",
  1245. kind: "Skill",
  1246. toolName: "Skill",
  1247. title: "Load skill",
  1248. input: {},
  1249. raw: {},
  1250. skillMetadata: {
  1251. name: "pptx",
  1252. qualifiedName: "document-skills:pptx",
  1253. pluginId: "document-skills@zcode-plugins-official",
  1254. source: "plugin",
  1255. },
  1256. },
  1257. now: 110,
  1258. });
  1259. const [step] = recordAgentStepTelemetryEvent({
  1260. taskId: "task-skill",
  1261. event: {
  1262. type: "tool_call_update",
  1263. taskId: "task-skill",
  1264. traceId: "trace-skill",
  1265. toolId: "tool-skill",
  1266. status: "completed",
  1267. kind: "Skill",
  1268. toolName: "Skill",
  1269. raw: {},
  1270. skillMetadata: {
  1271. name: "pptx",
  1272. qualifiedName: "document-skills:pptx",
  1273. pluginId: "document-skills@zcode-plugins-official",
  1274. source: "plugin",
  1275. },
  1276. },
  1277. now: 130,
  1278. });
  1279. expect(step?.eventExtraDetail).toMatchObject({
  1280. tool_name: "Skill",
  1281. skill_name: "pptx",
  1282. skill_qualified_name: "document-skills:pptx",
  1283. skill_plugin_id: "document-skills@zcode-plugins-official",
  1284. skill_source: "plugin",
  1285. });
  1286. recordAgentStepTelemetryEvent({
  1287. taskId: "task-skill",
  1288. event: {
  1289. type: "tool_call",
  1290. taskId: "task-skill",
  1291. traceId: "trace-skill",
  1292. toolId: "tool-bash",
  1293. kind: "Bash",
  1294. toolName: "Bash",
  1295. title: "Run command",
  1296. input: {},
  1297. raw: {},
  1298. skillMetadata: {
  1299. name: "pptx",
  1300. qualifiedName: "document-skills:pptx",
  1301. pluginId: "document-skills@zcode-plugins-official",
  1302. source: "plugin",
  1303. },
  1304. },
  1305. now: 140,
  1306. });
  1307. const [bashStep] = recordAgentStepTelemetryEvent({
  1308. taskId: "task-skill",
  1309. event: {
  1310. type: "tool_call_update",
  1311. taskId: "task-skill",
  1312. traceId: "trace-skill",
  1313. toolId: "tool-bash",
  1314. status: "completed",
  1315. kind: "Bash",
  1316. toolName: "Bash",
  1317. raw: {},
  1318. skillMetadata: {
  1319. name: "pptx",
  1320. qualifiedName: "document-skills:pptx",
  1321. pluginId: "document-skills@zcode-plugins-official",
  1322. source: "plugin",
  1323. },
  1324. },
  1325. now: 150,
  1326. });
  1327. expect(bashStep?.eventExtraDetail).not.toHaveProperty("skill_qualified_name");
  1328. expect(bashStep?.eventExtraDetail).not.toHaveProperty("skill_plugin_id");
  1329. expect(bashStep?.eventExtraDetail).not.toHaveProperty("skill_source");
  1330. expect(bashStep?.eventExtraDetail).not.toHaveProperty("skill_name");
  1331. });
  1332. it("uses the latest ordinary message chunk for generation tail finalize time", () => {
  1333. queuePromptTelemetry({
  1334. workspacePath: "/tmp/workspace-generation-tail",
  1335. taskId: "task-generation-tail",
  1336. messageId: "message-generation-tail",
  1337. sendTime: 100,
  1338. });
  1339. activatePromptTelemetry("task-generation-tail", "message-generation-tail");
  1340. recordAgentStepTelemetryEvent({
  1341. taskId: "task-generation-tail",
  1342. event: {
  1343. type: "agent_message_chunk",
  1344. taskId: "task-generation-tail",
  1345. traceId: "trace-generation-tail",
  1346. content: "first",
  1347. },
  1348. now: 200,
  1349. });
  1350. recordAgentStepTelemetryEvent({
  1351. taskId: "task-generation-tail",
  1352. event: {
  1353. type: "agent_message_chunk",
  1354. taskId: "task-generation-tail",
  1355. traceId: "trace-generation-tail",
  1356. content: "second",
  1357. },
  1358. now: 230,
  1359. });
  1360. expect(
  1361. recordAgentStepTelemetryEvent({
  1362. taskId: "task-generation-tail",
  1363. event: {
  1364. type: "task_complete",
  1365. taskId: "task-generation-tail",
  1366. traceId: "trace-generation-tail",
  1367. stopReason: "stop",
  1368. },
  1369. now: 260,
  1370. }),
  1371. ).toEqual([
  1372. expect.objectContaining({
  1373. eventExtraDetail: expect.objectContaining({
  1374. step_type: "generation",
  1375. duration_ms: "60",
  1376. generation_tail_finalize_ms: "30",
  1377. }),
  1378. }),
  1379. ]);
  1380. });
  1381. it("does not report generation tail finalize time when a tool call closes generation", () => {
  1382. queuePromptTelemetry({
  1383. workspacePath: "/tmp/workspace-generation-tool",
  1384. taskId: "task-generation-tool",
  1385. messageId: "message-generation-tool",
  1386. sendTime: 100,
  1387. });
  1388. activatePromptTelemetry("task-generation-tool", "message-generation-tool");
  1389. recordAgentStepTelemetryEvent({
  1390. taskId: "task-generation-tool",
  1391. event: {
  1392. type: "agent_message_chunk",
  1393. taskId: "task-generation-tool",
  1394. traceId: "trace-generation-tool",
  1395. content: "I will inspect it",
  1396. },
  1397. now: 200,
  1398. });
  1399. const finalized = recordAgentStepTelemetryEvent({
  1400. taskId: "task-generation-tool",
  1401. event: {
  1402. type: "tool_call",
  1403. taskId: "task-generation-tool",
  1404. traceId: "trace-generation-tool",
  1405. toolId: "tool-generation-tool",
  1406. kind: "Bash",
  1407. toolName: "Bash",
  1408. title: "Bash",
  1409. input: {},
  1410. raw: {},
  1411. },
  1412. now: 260,
  1413. });
  1414. expect(finalized).toHaveLength(1);
  1415. expect(finalized[0]?.eventExtraDetail).toEqual(
  1416. expect.objectContaining({
  1417. step_type: "generation",
  1418. duration_ms: "60",
  1419. generation_tail_finalize_ms: "",
  1420. }),
  1421. );
  1422. });
  1423. it("does not report generation tail finalize time for replayable recovered events", () => {
  1424. queuePromptTelemetry({
  1425. workspacePath: "/tmp/workspace-generation-replayable",
  1426. taskId: "task-generation-replayable",
  1427. messageId: "message-generation-replayable",
  1428. sendTime: 100,
  1429. });
  1430. activatePromptTelemetry("task-generation-replayable", "message-generation-replayable");
  1431. recordAgentStepTelemetryEvent({
  1432. taskId: "task-generation-replayable",
  1433. event: {
  1434. type: "agent_message_chunk",
  1435. taskId: "task-generation-replayable",
  1436. traceId: "trace-generation-replayable",
  1437. content: "done",
  1438. },
  1439. clientMode: "web-remote-replayable",
  1440. now: 200,
  1441. });
  1442. const finalized = recordAgentStepTelemetryEvent({
  1443. taskId: "task-generation-replayable",
  1444. event: {
  1445. type: "task_complete",
  1446. taskId: "task-generation-replayable",
  1447. traceId: "trace-generation-replayable",
  1448. stopReason: "stop",
  1449. },
  1450. clientMode: "web-remote-replayable",
  1451. now: 260,
  1452. });
  1453. expect(finalized).toHaveLength(1);
  1454. expect(finalized[0]?.eventExtraDetail).toEqual(
  1455. expect.objectContaining({
  1456. step_type: "generation",
  1457. duration_ms: "60",
  1458. generation_tail_finalize_ms: "",
  1459. }),
  1460. );
  1461. });
  1462. it("does not count parented agent chunks as generation steps", () => {
  1463. queuePromptTelemetry({
  1464. workspacePath: "/tmp/workspace-parented-agent-chunk",
  1465. taskId: "task-parented-agent-chunk",
  1466. messageId: "message-parented-agent-chunk",
  1467. sendTime: 100,
  1468. });
  1469. activatePromptTelemetry("task-parented-agent-chunk", "message-parented-agent-chunk");
  1470. recordAgentStepTelemetryEvent({
  1471. taskId: "task-parented-agent-chunk",
  1472. event: {
  1473. type: "tool_call",
  1474. taskId: "task-parented-agent-chunk",
  1475. traceId: "trace-parented-agent-chunk",
  1476. toolId: "tool-parent-agent",
  1477. kind: "agent",
  1478. toolName: "Task",
  1479. title: "Task",
  1480. input: {},
  1481. raw: {},
  1482. },
  1483. now: 150,
  1484. });
  1485. expect(
  1486. recordAgentStepTelemetryEvent({
  1487. taskId: "task-parented-agent-chunk",
  1488. event: {
  1489. type: "agent_message_chunk",
  1490. taskId: "task-parented-agent-chunk",
  1491. traceId: "trace-parented-agent-chunk",
  1492. parentToolUseId: "tool-parent-agent",
  1493. content: "subagent output",
  1494. },
  1495. now: 200,
  1496. }),
  1497. ).toEqual([]);
  1498. const finalized = recordAgentStepTelemetryEvent({
  1499. taskId: "task-parented-agent-chunk",
  1500. event: {
  1501. type: "task_complete",
  1502. taskId: "task-parented-agent-chunk",
  1503. traceId: "trace-parented-agent-chunk",
  1504. stopReason: "stop",
  1505. },
  1506. now: 260,
  1507. });
  1508. expect(finalized).toHaveLength(1);
  1509. expect(finalized[0]?.eventExtraDetail).toEqual(
  1510. expect.objectContaining({
  1511. step_type: "tool_call",
  1512. tool_call_id: "tool-parent-agent",
  1513. generation_tail_finalize_ms: "",
  1514. }),
  1515. );
  1516. });
  1517. it("attributes permission waiting to the tool step while keeping wall-clock durations", () => {
  1518. queuePromptTelemetry({
  1519. workspacePath: "/tmp/workspace-permission",
  1520. taskId: "task-permission",
  1521. messageId: "message-permission",
  1522. sendTime: 100,
  1523. });
  1524. activatePromptTelemetry("task-permission", "message-permission");
  1525. recordAgentStepTelemetryEvent({
  1526. taskId: "task-permission",
  1527. event: {
  1528. type: "tool_call",
  1529. taskId: "task-permission",
  1530. traceId: "trace-permission",
  1531. toolId: "tool-permission",
  1532. kind: "bash",
  1533. toolName: "bash",
  1534. title: "Run command",
  1535. input: {},
  1536. raw: {},
  1537. },
  1538. now: 200,
  1539. });
  1540. recordPromptPermissionRequest({
  1541. taskId: "task-permission",
  1542. requestId: "request-permission",
  1543. toolCallId: "tool-permission",
  1544. now: 250,
  1545. });
  1546. // replay/重复投递不能重置等待起点
  1547. recordPromptPermissionRequest({
  1548. taskId: "task-permission",
  1549. requestId: "request-permission",
  1550. toolCallId: "tool-permission",
  1551. now: 300,
  1552. });
  1553. recordPromptPermissionResponse({
  1554. taskId: "task-permission",
  1555. requestId: "request-permission",
  1556. now: 400,
  1557. });
  1558. // 本地响应与 stream response 都可能触发,第二次必须幂等
  1559. recordPromptPermissionResponse({
  1560. taskId: "task-permission",
  1561. requestId: "request-permission",
  1562. now: 450,
  1563. });
  1564. const [toolStep] = recordAgentStepTelemetryEvent({
  1565. taskId: "task-permission",
  1566. event: {
  1567. type: "tool_call_update",
  1568. taskId: "task-permission",
  1569. traceId: "trace-permission",
  1570. toolId: "tool-permission",
  1571. status: "completed",
  1572. kind: "bash",
  1573. toolName: "bash",
  1574. raw: {},
  1575. },
  1576. now: 500,
  1577. });
  1578. const completion = finalizePromptTelemetry({
  1579. taskId: "task-permission",
  1580. status: "success",
  1581. finishedAt: 700,
  1582. });
  1583. expect(toolStep?.eventExtraDetail).toMatchObject({
  1584. step_type: "tool_call",
  1585. duration_ms: "300",
  1586. waiting_ms: "150",
  1587. });
  1588. expect(completion?.eventExtraDetail).toMatchObject({
  1589. duration_ms: "600",
  1590. waiting_ms: "150",
  1591. });
  1592. });
  1593. it("sums permission waits from multiple tool calls into message completion", () => {
  1594. queuePromptTelemetry({
  1595. workspacePath: "/tmp/workspace-permission-sum",
  1596. taskId: "task-permission-sum",
  1597. messageId: "message-permission-sum",
  1598. sendTime: 100,
  1599. });
  1600. activatePromptTelemetry("task-permission-sum", "message-permission-sum");
  1601. const runTool = (
  1602. toolId: string,
  1603. requestId: string,
  1604. startedAt: number,
  1605. requestedAt: number,
  1606. respondedAt: number,
  1607. finishedAt: number,
  1608. ) => {
  1609. recordAgentStepTelemetryEvent({
  1610. taskId: "task-permission-sum",
  1611. event: {
  1612. type: "tool_call",
  1613. taskId: "task-permission-sum",
  1614. traceId: "trace-permission-sum",
  1615. toolId,
  1616. kind: "bash",
  1617. toolName: "bash",
  1618. title: "Run command",
  1619. input: {},
  1620. raw: {},
  1621. },
  1622. now: startedAt,
  1623. });
  1624. recordPromptPermissionRequest({
  1625. taskId: "task-permission-sum",
  1626. requestId,
  1627. toolCallId: toolId,
  1628. now: requestedAt,
  1629. });
  1630. recordPromptPermissionResponse({
  1631. taskId: "task-permission-sum",
  1632. requestId,
  1633. now: respondedAt,
  1634. });
  1635. return recordAgentStepTelemetryEvent({
  1636. taskId: "task-permission-sum",
  1637. event: {
  1638. type: "tool_call_update",
  1639. taskId: "task-permission-sum",
  1640. traceId: "trace-permission-sum",
  1641. toolId,
  1642. status: "completed",
  1643. kind: "bash",
  1644. toolName: "bash",
  1645. raw: {},
  1646. },
  1647. now: finishedAt,
  1648. })[0];
  1649. };
  1650. const firstTool = runTool("tool-1", "request-1", 150, 200, 250, 300);
  1651. const secondTool = runTool("tool-2", "request-2", 350, 400, 550, 600);
  1652. const completion = finalizePromptTelemetry({
  1653. taskId: "task-permission-sum",
  1654. status: "success",
  1655. finishedAt: 700,
  1656. });
  1657. expect(firstTool?.eventExtraDetail.waiting_ms).toBe("50");
  1658. expect(secondTool?.eventExtraDetail.waiting_ms).toBe("150");
  1659. expect(completion?.eventExtraDetail).toMatchObject({
  1660. duration_ms: "600",
  1661. waiting_ms: "200",
  1662. });
  1663. });
  1664. it("accumulates repeated waits on one tool without attributing unmatched waits to it", () => {
  1665. queuePromptTelemetry({
  1666. workspacePath: "/tmp/workspace-permission-repeat",
  1667. taskId: "task-permission-repeat",
  1668. messageId: "message-permission-repeat",
  1669. sendTime: 100,
  1670. });
  1671. activatePromptTelemetry("task-permission-repeat", "message-permission-repeat");
  1672. recordAgentStepTelemetryEvent({
  1673. taskId: "task-permission-repeat",
  1674. event: {
  1675. type: "tool_call",
  1676. taskId: "task-permission-repeat",
  1677. traceId: "trace-permission-repeat",
  1678. toolId: "tool-permission-repeat",
  1679. kind: "bash",
  1680. toolName: "bash",
  1681. title: "Run command",
  1682. input: {},
  1683. raw: {},
  1684. },
  1685. now: 150,
  1686. });
  1687. recordPromptPermissionRequest({
  1688. taskId: "task-permission-repeat",
  1689. requestId: "request-repeat-1",
  1690. toolCallId: "tool-permission-repeat",
  1691. now: 200,
  1692. });
  1693. recordPromptPermissionResponse({
  1694. taskId: "task-permission-repeat",
  1695. requestId: "request-repeat-1",
  1696. now: 250,
  1697. });
  1698. recordPromptPermissionRequest({
  1699. taskId: "task-permission-repeat",
  1700. requestId: "request-repeat-2",
  1701. toolCallId: "tool-permission-repeat",
  1702. now: 300,
  1703. });
  1704. recordPromptPermissionResponse({
  1705. taskId: "task-permission-repeat",
  1706. requestId: "request-repeat-2",
  1707. now: 400,
  1708. });
  1709. recordPromptPermissionRequest({
  1710. taskId: "task-permission-repeat",
  1711. requestId: "request-unmatched",
  1712. toolCallId: "another-tool",
  1713. now: 410,
  1714. });
  1715. recordPromptPermissionResponse({
  1716. taskId: "task-permission-repeat",
  1717. requestId: "request-unmatched",
  1718. now: 460,
  1719. });
  1720. const [toolStep] = recordAgentStepTelemetryEvent({
  1721. taskId: "task-permission-repeat",
  1722. event: {
  1723. type: "tool_call_update",
  1724. taskId: "task-permission-repeat",
  1725. traceId: "trace-permission-repeat",
  1726. toolId: "tool-permission-repeat",
  1727. status: "completed",
  1728. kind: "bash",
  1729. toolName: "bash",
  1730. raw: {},
  1731. },
  1732. now: 500,
  1733. });
  1734. const completion = finalizePromptTelemetry({
  1735. taskId: "task-permission-repeat",
  1736. status: "success",
  1737. finishedAt: 600,
  1738. });
  1739. expect(toolStep?.eventExtraDetail.waiting_ms).toBe("150");
  1740. expect(completion?.eventExtraDetail.waiting_ms).toBe("200");
  1741. });
  1742. it("settles unanswered permission waits when the task terminates", () => {
  1743. queuePromptTelemetry({
  1744. workspacePath: "/tmp/workspace-permission-stop",
  1745. taskId: "task-permission-stop",
  1746. messageId: "message-permission-stop",
  1747. sendTime: 100,
  1748. });
  1749. activatePromptTelemetry("task-permission-stop", "message-permission-stop");
  1750. recordAgentStepTelemetryEvent({
  1751. taskId: "task-permission-stop",
  1752. event: {
  1753. type: "tool_call",
  1754. taskId: "task-permission-stop",
  1755. traceId: "trace-permission-stop",
  1756. toolId: "tool-permission-stop",
  1757. kind: "bash",
  1758. toolName: "bash",
  1759. title: "Run command",
  1760. input: {},
  1761. raw: {},
  1762. },
  1763. now: 200,
  1764. });
  1765. recordPromptPermissionRequest({
  1766. taskId: "task-permission-stop",
  1767. requestId: "request-permission-stop",
  1768. toolCallId: "tool-permission-stop",
  1769. now: 300,
  1770. });
  1771. const [toolStep] = recordAgentStepTelemetryEvent({
  1772. taskId: "task-permission-stop",
  1773. event: {
  1774. type: "task_error",
  1775. taskId: "task-permission-stop",
  1776. traceId: "trace-permission-stop",
  1777. code: "USER_INTERRUPT",
  1778. error: "stopped",
  1779. },
  1780. now: 600,
  1781. });
  1782. const completion = finalizePromptTelemetry({
  1783. taskId: "task-permission-stop",
  1784. status: "user_interrupt",
  1785. finishedAt: 600,
  1786. });
  1787. expect(toolStep?.eventExtraDetail).toMatchObject({
  1788. step_type: "tool_call",
  1789. duration_ms: "400",
  1790. waiting_ms: "300",
  1791. status: "fail",
  1792. });
  1793. expect(completion?.eventExtraDetail).toMatchObject({
  1794. duration_ms: "500",
  1795. waiting_ms: "300",
  1796. });
  1797. });
  1798. it("restores settled permission waiting when terminal tool update has no opening tool call", () => {
  1799. queuePromptTelemetry({
  1800. workspacePath: "/tmp/workspace-permission-replay-settled",
  1801. taskId: "task-permission-replay-settled",
  1802. messageId: "message-permission-replay-settled",
  1803. sendTime: 100,
  1804. });
  1805. activatePromptTelemetry("task-permission-replay-settled", "message-permission-replay-settled");
  1806. recordPromptPermissionRequest({
  1807. taskId: "task-permission-replay-settled",
  1808. requestId: "request-permission-replay-settled",
  1809. toolCallId: "tool-permission-replay-settled",
  1810. now: 200,
  1811. });
  1812. recordPromptPermissionRequest({
  1813. taskId: "task-permission-replay-settled",
  1814. requestId: "request-permission-replay-overlap",
  1815. toolCallId: "tool-permission-replay-settled",
  1816. now: 250,
  1817. });
  1818. recordPromptPermissionResponse({
  1819. taskId: "task-permission-replay-settled",
  1820. requestId: "request-permission-replay-settled",
  1821. now: 350,
  1822. });
  1823. recordPromptPermissionResponse({
  1824. taskId: "task-permission-replay-settled",
  1825. requestId: "request-permission-replay-overlap",
  1826. now: 450,
  1827. });
  1828. const [toolStep] = recordAgentStepTelemetryEvent({
  1829. taskId: "task-permission-replay-settled",
  1830. event: {
  1831. type: "tool_call_update",
  1832. taskId: "task-permission-replay-settled",
  1833. traceId: "trace-permission-replay-settled",
  1834. toolId: "tool-permission-replay-settled",
  1835. status: "completed",
  1836. kind: "bash",
  1837. toolName: "bash",
  1838. raw: {},
  1839. },
  1840. now: 500,
  1841. });
  1842. const completion = finalizePromptTelemetry({
  1843. taskId: "task-permission-replay-settled",
  1844. status: "success",
  1845. finishedAt: 600,
  1846. });
  1847. expect(toolStep?.eventExtraDetail).toMatchObject({
  1848. step_type: "tool_call",
  1849. duration_ms: "350",
  1850. waiting_ms: "350",
  1851. });
  1852. expect(completion?.eventExtraDetail).toMatchObject({
  1853. duration_ms: "500",
  1854. waiting_ms: "350",
  1855. });
  1856. });
  1857. it("uses the pending request time when terminal tool update settles an unanswered wait", () => {
  1858. queuePromptTelemetry({
  1859. workspacePath: "/tmp/workspace-permission-replay-open",
  1860. taskId: "task-permission-replay-open",
  1861. messageId: "message-permission-replay-open",
  1862. sendTime: 100,
  1863. });
  1864. activatePromptTelemetry("task-permission-replay-open", "message-permission-replay-open");
  1865. recordPromptPermissionRequest({
  1866. taskId: "task-permission-replay-open",
  1867. requestId: "request-permission-replay-open",
  1868. toolCallId: "tool-permission-replay-open",
  1869. now: 200,
  1870. });
  1871. const [toolStep] = recordAgentStepTelemetryEvent({
  1872. taskId: "task-permission-replay-open",
  1873. event: {
  1874. type: "tool_call_update",
  1875. taskId: "task-permission-replay-open",
  1876. traceId: "trace-permission-replay-open",
  1877. toolId: "tool-permission-replay-open",
  1878. status: "failed",
  1879. kind: "bash",
  1880. toolName: "bash",
  1881. error: "stopped before permission response",
  1882. raw: {},
  1883. },
  1884. now: 500,
  1885. });
  1886. const completion = finalizePromptTelemetry({
  1887. taskId: "task-permission-replay-open",
  1888. status: "user_interrupt",
  1889. finishedAt: 500,
  1890. });
  1891. expect(toolStep?.eventExtraDetail).toMatchObject({
  1892. step_type: "tool_call",
  1893. duration_ms: "300",
  1894. waiting_ms: "300",
  1895. status: "fail",
  1896. });
  1897. expect(completion?.eventExtraDetail).toMatchObject({
  1898. duration_ms: "400",
  1899. waiting_ms: "300",
  1900. });
  1901. });
  1902. it("uses actual model request fields for agent_step telemetry", () => {
  1903. queuePromptTelemetry({
  1904. workspacePath: "/tmp/workspace-step-model",
  1905. taskId: "task-step-model",
  1906. messageId: "message-step-model",
  1907. inputId: "input-step-model",
  1908. sendTime: 100,
  1909. extraDetail: {
  1910. model_name: "account:bigmodel-start-plan/GLM-5.2",
  1911. model_provider: "provider-custom",
  1912. },
  1913. });
  1914. activatePromptTelemetry("task-step-model", "message-step-model");
  1915. recordPromptModelRequestStarted("task-step-model", {
  1916. type: "task_network_debug_status",
  1917. taskId: "task-step-model",
  1918. traceId: "trace-step-model",
  1919. inputId: "input-step-model",
  1920. eventKey: "event-step-model",
  1921. statusType: "model_request_started",
  1922. requestId: "request-step-model",
  1923. providerId: "provider-custom",
  1924. modelId: "GLM-5.2",
  1925. requestHeaders: {},
  1926. responseHeaders: {},
  1927. requestHeaderCount: 0,
  1928. responseHeaderCount: 0,
  1929. });
  1930. recordAgentStepTelemetryEvent({
  1931. taskId: "task-step-model",
  1932. event: {
  1933. type: "agent_thought_chunk",
  1934. taskId: "task-step-model",
  1935. traceId: "trace-step-model",
  1936. content: "thinking",
  1937. },
  1938. now: 110,
  1939. });
  1940. const [reasoningStep] = recordAgentStepTelemetryEvent({
  1941. taskId: "task-step-model",
  1942. event: {
  1943. type: "agent_message_chunk",
  1944. taskId: "task-step-model",
  1945. traceId: "trace-step-model",
  1946. content: "done",
  1947. },
  1948. now: 150,
  1949. });
  1950. recordPromptTokenUsageDelta({
  1951. taskId: "task-step-model",
  1952. eventKey: "usage-step-model",
  1953. requestId: "request-step-model",
  1954. modelName: "provider-custom/GLM-5.2",
  1955. modelProvider: "provider-custom",
  1956. providerName: "runtime.example.com",
  1957. usage: {
  1958. inputTokens: 80,
  1959. outputTokens: 20,
  1960. totalTokens: 100,
  1961. reasoningTokens: 6,
  1962. cachedInputTokens: 30,
  1963. cachedWriteInputTokens: 4,
  1964. },
  1965. });
  1966. const [generationStep] = recordAgentStepTelemetryEvent({
  1967. taskId: "task-step-model",
  1968. event: {
  1969. type: "task_complete",
  1970. taskId: "task-step-model",
  1971. traceId: "trace-step-model-complete",
  1972. stopReason: "complete",
  1973. },
  1974. now: 180,
  1975. });
  1976. expect(reasoningStep).toEqual({
  1977. taskId: "task-step-model",
  1978. messageId: "message-step-model",
  1979. eventExtraDetail: expect.objectContaining({
  1980. model_name: "provider-custom/GLM-5.2",
  1981. model_provider: "provider-custom",
  1982. input_tokens: "0",
  1983. total_tokens: "0",
  1984. }),
  1985. });
  1986. expect(generationStep).toEqual({
  1987. taskId: "task-step-model",
  1988. messageId: "message-step-model",
  1989. eventExtraDetail: expect.objectContaining({
  1990. model_name: "provider-custom/GLM-5.2",
  1991. model_provider: "provider-custom",
  1992. provider_name: "runtime.example.com",
  1993. model_request_id: "request-step-model",
  1994. model_request_count: "1",
  1995. token_usage_scope: "model_request",
  1996. input_tokens: "80",
  1997. output_tokens: "20",
  1998. reasoning_tokens: "6",
  1999. cached_tokens: "30",
  2000. cache_write_input_tokens: "4",
  2001. total_tokens: "100",
  2002. }),
  2003. });
  2004. });
  2005. it("attributes foreground subagent usage to its parent Agent tool step", () => {
  2006. queuePromptTelemetry({
  2007. workspacePath: "/tmp/workspace-subagent-step",
  2008. taskId: "task-subagent-step",
  2009. messageId: "message-subagent-step",
  2010. sendTime: 100,
  2011. });
  2012. activatePromptTelemetry("task-subagent-step", "message-subagent-step");
  2013. recordAgentStepTelemetryEvent({
  2014. taskId: "task-subagent-step",
  2015. event: {
  2016. type: "tool_call",
  2017. taskId: "task-subagent-step",
  2018. traceId: "trace-agent-tool",
  2019. toolId: "tool-agent",
  2020. kind: "Agent",
  2021. toolName: "Agent",
  2022. title: "Agent",
  2023. input: {},
  2024. raw: {},
  2025. },
  2026. now: 120,
  2027. });
  2028. recordSubagentToolAttribution({
  2029. taskId: "task-subagent-step",
  2030. toolCallId: "tool-agent",
  2031. requestIds: ["child-request-1", "child-request-2"],
  2032. requestCount: 2,
  2033. modelName: "child-provider/child-model",
  2034. modelProvider: "child-provider",
  2035. providerName: "child.example.com",
  2036. agentId: "agent-child",
  2037. usage: {
  2038. inputTokens: 150,
  2039. outputTokens: 50,
  2040. totalTokens: 200,
  2041. reasoningTokens: 12,
  2042. cachedInputTokens: 40,
  2043. cachedWriteInputTokens: 5,
  2044. },
  2045. });
  2046. expect(
  2047. recordAgentStepTelemetryEvent({
  2048. taskId: "task-subagent-step",
  2049. event: {
  2050. type: "tool_call_update",
  2051. taskId: "task-subagent-step",
  2052. traceId: "trace-agent-tool-complete",
  2053. toolId: "tool-agent",
  2054. status: "completed",
  2055. kind: "Agent",
  2056. toolName: "Agent",
  2057. raw: {},
  2058. },
  2059. now: 220,
  2060. }),
  2061. ).toEqual([
  2062. {
  2063. taskId: "task-subagent-step",
  2064. messageId: "message-subagent-step",
  2065. eventExtraDetail: expect.objectContaining({
  2066. model_name: "child-provider/child-model",
  2067. model_provider: "child-provider",
  2068. provider_name: "child.example.com",
  2069. agent_id: "agent-child",
  2070. model_request_id: "",
  2071. model_request_count: "2",
  2072. token_usage_scope: "subagent_requests",
  2073. input_tokens: "150",
  2074. output_tokens: "50",
  2075. total_tokens: "200",
  2076. }),
  2077. },
  2078. ]);
  2079. });
  2080. it("keeps a direct tool request usage separate from foreground subagent usage", () => {
  2081. queuePromptTelemetry({
  2082. workspacePath: "/tmp/workspace-direct-agent-tool",
  2083. taskId: "task-direct-agent-tool",
  2084. messageId: "message-direct-agent-tool",
  2085. inputId: "input-direct-agent-tool",
  2086. sendTime: 100,
  2087. });
  2088. activatePromptTelemetry("task-direct-agent-tool", "message-direct-agent-tool");
  2089. recordPromptModelRequestStarted("task-direct-agent-tool", {
  2090. type: "task_network_debug_status",
  2091. taskId: "task-direct-agent-tool",
  2092. traceId: "trace-main-request",
  2093. inputId: "input-direct-agent-tool",
  2094. eventKey: "main-request-started",
  2095. statusType: "model_request_started",
  2096. requestId: "main-request",
  2097. providerId: "main-provider",
  2098. modelId: "main-model",
  2099. requestHeaders: {},
  2100. responseHeaders: {},
  2101. requestHeaderCount: 0,
  2102. responseHeaderCount: 0,
  2103. });
  2104. recordPromptTokenUsageDelta({
  2105. taskId: "task-direct-agent-tool",
  2106. eventKey: "main-request-usage",
  2107. requestId: "main-request",
  2108. modelName: "main-provider/main-model",
  2109. modelProvider: "main-provider",
  2110. providerName: "main.example.com",
  2111. usage: {
  2112. inputTokens: 75,
  2113. outputTokens: 25,
  2114. totalTokens: 100,
  2115. },
  2116. });
  2117. const [mainRequestStep] = recordAgentStepTelemetryEvent({
  2118. taskId: "task-direct-agent-tool",
  2119. event: {
  2120. type: "tool_call",
  2121. taskId: "task-direct-agent-tool",
  2122. traceId: "trace-agent-tool",
  2123. toolId: "tool-agent-direct",
  2124. kind: "Agent",
  2125. toolName: "Agent",
  2126. title: "Agent",
  2127. input: {},
  2128. raw: {},
  2129. },
  2130. now: 120,
  2131. });
  2132. recordSubagentToolAttribution({
  2133. taskId: "task-direct-agent-tool",
  2134. toolCallId: "tool-agent-direct",
  2135. requestIds: ["child-request"],
  2136. requestCount: 1,
  2137. modelName: "child-provider/child-model",
  2138. modelProvider: "child-provider",
  2139. providerName: "child.example.com",
  2140. agentId: "agent-child",
  2141. usage: {
  2142. inputTokens: 160,
  2143. outputTokens: 40,
  2144. totalTokens: 200,
  2145. },
  2146. });
  2147. const [childToolStep] = recordAgentStepTelemetryEvent({
  2148. taskId: "task-direct-agent-tool",
  2149. event: {
  2150. type: "tool_call_update",
  2151. taskId: "task-direct-agent-tool",
  2152. traceId: "trace-agent-tool-complete",
  2153. toolId: "tool-agent-direct",
  2154. status: "completed",
  2155. kind: "Agent",
  2156. toolName: "Agent",
  2157. raw: {},
  2158. },
  2159. now: 220,
  2160. });
  2161. expect(mainRequestStep?.eventExtraDetail).toMatchObject({
  2162. step_type: "generation",
  2163. model_name: "main-provider/main-model",
  2164. token_usage_scope: "model_request",
  2165. total_tokens: "100",
  2166. });
  2167. expect(childToolStep?.eventExtraDetail).toMatchObject({
  2168. step_type: "tool_call",
  2169. model_name: "child-provider/child-model",
  2170. agent_id: "agent-child",
  2171. token_usage_scope: "subagent_requests",
  2172. total_tokens: "200",
  2173. });
  2174. });
  2175. it("uses the first tool call as time_to_first_token when it arrives before text", () => {
  2176. queuePromptTelemetry({
  2177. workspacePath: "/tmp/workspace-tool-first",
  2178. taskId: "task-tool-first",
  2179. messageId: "message-tool-first",
  2180. sendTime: 100,
  2181. });
  2182. activatePromptTelemetry("task-tool-first", "message-tool-first");
  2183. recordAgentStepTelemetryEvent({
  2184. taskId: "task-tool-first",
  2185. event: {
  2186. type: "tool_call",
  2187. taskId: "task-tool-first",
  2188. traceId: "trace-tool-first",
  2189. toolId: "tool-first",
  2190. kind: "read",
  2191. toolName: "read_file",
  2192. title: "Read file",
  2193. input: {},
  2194. raw: {},
  2195. },
  2196. now: 175,
  2197. });
  2198. expect(
  2199. finalizePromptTelemetry({
  2200. taskId: "task-tool-first",
  2201. status: "success",
  2202. finishedAt: 250,
  2203. })?.eventExtraDetail.time_to_first_token,
  2204. ).toBe("75");
  2205. });
  2206. });
  2207. describe("composeAgentComposition:fg / bg / wf 三维组合", () => {
  2208. it("枚举八个值", async () => {
  2209. const { composeAgentComposition } = await import("@/lib/messageTelemetry.js");
  2210. const compose = (fg: boolean, bg: boolean, wf: boolean) =>
  2211. composeAgentComposition({
  2212. hasForegroundSubagentResult: fg,
  2213. hasBackgroundSubagentResult: bg,
  2214. hasWorkflowResult: wf,
  2215. });
  2216. expect(compose(false, false, false)).toBe("main_only");
  2217. expect(compose(true, false, false)).toBe("main_plus_fg");
  2218. expect(compose(false, true, false)).toBe("main_plus_bg");
  2219. expect(compose(false, false, true)).toBe("main_plus_wf");
  2220. expect(compose(true, true, false)).toBe("main_plus_fg_bg");
  2221. expect(compose(true, false, true)).toBe("main_plus_fg_wf");
  2222. expect(compose(false, true, true)).toBe("main_plus_bg_wf");
  2223. expect(compose(true, true, true)).toBe("main_plus_fg_bg_wf");
  2224. });
  2225. });