messageTelemetry.test.ts 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288
  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("Skill tool step 携带解析后的 skill metadata,普通 tool step 不携带", () => {
  1180. queuePromptTelemetry({
  1181. workspacePath: "/tmp/workspace-skill",
  1182. taskId: "task-skill",
  1183. messageId: "message-skill",
  1184. sendTime: 100,
  1185. });
  1186. activatePromptTelemetry("task-skill", "message-skill");
  1187. recordAgentStepTelemetryEvent({
  1188. taskId: "task-skill",
  1189. event: {
  1190. type: "tool_call",
  1191. taskId: "task-skill",
  1192. traceId: "trace-skill",
  1193. toolId: "tool-skill",
  1194. kind: "Skill",
  1195. toolName: "Skill",
  1196. title: "Load skill",
  1197. input: {},
  1198. raw: {},
  1199. skillMetadata: {
  1200. qualifiedName: "document-skills:pptx",
  1201. pluginId: "document-skills@zcode-plugins-official",
  1202. source: "plugin",
  1203. },
  1204. },
  1205. now: 110,
  1206. });
  1207. const [step] = recordAgentStepTelemetryEvent({
  1208. taskId: "task-skill",
  1209. event: {
  1210. type: "tool_call_update",
  1211. taskId: "task-skill",
  1212. traceId: "trace-skill",
  1213. toolId: "tool-skill",
  1214. status: "completed",
  1215. kind: "Skill",
  1216. toolName: "Skill",
  1217. raw: {},
  1218. skillMetadata: {
  1219. qualifiedName: "document-skills:pptx",
  1220. pluginId: "document-skills@zcode-plugins-official",
  1221. source: "plugin",
  1222. },
  1223. },
  1224. now: 130,
  1225. });
  1226. expect(step?.eventExtraDetail).toMatchObject({
  1227. tool_name: "Skill",
  1228. skill_qualified_name: "document-skills:pptx",
  1229. skill_plugin_id: "document-skills@zcode-plugins-official",
  1230. skill_source: "plugin",
  1231. });
  1232. recordAgentStepTelemetryEvent({
  1233. taskId: "task-skill",
  1234. event: {
  1235. type: "tool_call",
  1236. taskId: "task-skill",
  1237. traceId: "trace-skill",
  1238. toolId: "tool-bash",
  1239. kind: "Bash",
  1240. toolName: "Bash",
  1241. title: "Run command",
  1242. input: {},
  1243. raw: {},
  1244. skillMetadata: {
  1245. qualifiedName: "document-skills:pptx",
  1246. pluginId: "document-skills@zcode-plugins-official",
  1247. source: "plugin",
  1248. },
  1249. },
  1250. now: 140,
  1251. });
  1252. const [bashStep] = recordAgentStepTelemetryEvent({
  1253. taskId: "task-skill",
  1254. event: {
  1255. type: "tool_call_update",
  1256. taskId: "task-skill",
  1257. traceId: "trace-skill",
  1258. toolId: "tool-bash",
  1259. status: "completed",
  1260. kind: "Bash",
  1261. toolName: "Bash",
  1262. raw: {},
  1263. skillMetadata: {
  1264. qualifiedName: "document-skills:pptx",
  1265. pluginId: "document-skills@zcode-plugins-official",
  1266. source: "plugin",
  1267. },
  1268. },
  1269. now: 150,
  1270. });
  1271. expect(bashStep?.eventExtraDetail).not.toHaveProperty("skill_qualified_name");
  1272. expect(bashStep?.eventExtraDetail).not.toHaveProperty("skill_plugin_id");
  1273. expect(bashStep?.eventExtraDetail).not.toHaveProperty("skill_source");
  1274. });
  1275. it("uses the latest ordinary message chunk for generation tail finalize time", () => {
  1276. queuePromptTelemetry({
  1277. workspacePath: "/tmp/workspace-generation-tail",
  1278. taskId: "task-generation-tail",
  1279. messageId: "message-generation-tail",
  1280. sendTime: 100,
  1281. });
  1282. activatePromptTelemetry("task-generation-tail", "message-generation-tail");
  1283. recordAgentStepTelemetryEvent({
  1284. taskId: "task-generation-tail",
  1285. event: {
  1286. type: "agent_message_chunk",
  1287. taskId: "task-generation-tail",
  1288. traceId: "trace-generation-tail",
  1289. content: "first",
  1290. },
  1291. now: 200,
  1292. });
  1293. recordAgentStepTelemetryEvent({
  1294. taskId: "task-generation-tail",
  1295. event: {
  1296. type: "agent_message_chunk",
  1297. taskId: "task-generation-tail",
  1298. traceId: "trace-generation-tail",
  1299. content: "second",
  1300. },
  1301. now: 230,
  1302. });
  1303. expect(
  1304. recordAgentStepTelemetryEvent({
  1305. taskId: "task-generation-tail",
  1306. event: {
  1307. type: "task_complete",
  1308. taskId: "task-generation-tail",
  1309. traceId: "trace-generation-tail",
  1310. stopReason: "stop",
  1311. },
  1312. now: 260,
  1313. }),
  1314. ).toEqual([
  1315. expect.objectContaining({
  1316. eventExtraDetail: expect.objectContaining({
  1317. step_type: "generation",
  1318. duration_ms: "60",
  1319. generation_tail_finalize_ms: "30",
  1320. }),
  1321. }),
  1322. ]);
  1323. });
  1324. it("does not report generation tail finalize time when a tool call closes generation", () => {
  1325. queuePromptTelemetry({
  1326. workspacePath: "/tmp/workspace-generation-tool",
  1327. taskId: "task-generation-tool",
  1328. messageId: "message-generation-tool",
  1329. sendTime: 100,
  1330. });
  1331. activatePromptTelemetry("task-generation-tool", "message-generation-tool");
  1332. recordAgentStepTelemetryEvent({
  1333. taskId: "task-generation-tool",
  1334. event: {
  1335. type: "agent_message_chunk",
  1336. taskId: "task-generation-tool",
  1337. traceId: "trace-generation-tool",
  1338. content: "I will inspect it",
  1339. },
  1340. now: 200,
  1341. });
  1342. const finalized = recordAgentStepTelemetryEvent({
  1343. taskId: "task-generation-tool",
  1344. event: {
  1345. type: "tool_call",
  1346. taskId: "task-generation-tool",
  1347. traceId: "trace-generation-tool",
  1348. toolId: "tool-generation-tool",
  1349. kind: "Bash",
  1350. toolName: "Bash",
  1351. title: "Bash",
  1352. input: {},
  1353. raw: {},
  1354. },
  1355. now: 260,
  1356. });
  1357. expect(finalized).toHaveLength(1);
  1358. expect(finalized[0]?.eventExtraDetail).toEqual(
  1359. expect.objectContaining({
  1360. step_type: "generation",
  1361. duration_ms: "60",
  1362. generation_tail_finalize_ms: "",
  1363. }),
  1364. );
  1365. });
  1366. it("does not report generation tail finalize time for replayable recovered events", () => {
  1367. queuePromptTelemetry({
  1368. workspacePath: "/tmp/workspace-generation-replayable",
  1369. taskId: "task-generation-replayable",
  1370. messageId: "message-generation-replayable",
  1371. sendTime: 100,
  1372. });
  1373. activatePromptTelemetry("task-generation-replayable", "message-generation-replayable");
  1374. recordAgentStepTelemetryEvent({
  1375. taskId: "task-generation-replayable",
  1376. event: {
  1377. type: "agent_message_chunk",
  1378. taskId: "task-generation-replayable",
  1379. traceId: "trace-generation-replayable",
  1380. content: "done",
  1381. },
  1382. clientMode: "web-remote-replayable",
  1383. now: 200,
  1384. });
  1385. const finalized = recordAgentStepTelemetryEvent({
  1386. taskId: "task-generation-replayable",
  1387. event: {
  1388. type: "task_complete",
  1389. taskId: "task-generation-replayable",
  1390. traceId: "trace-generation-replayable",
  1391. stopReason: "stop",
  1392. },
  1393. clientMode: "web-remote-replayable",
  1394. now: 260,
  1395. });
  1396. expect(finalized).toHaveLength(1);
  1397. expect(finalized[0]?.eventExtraDetail).toEqual(
  1398. expect.objectContaining({
  1399. step_type: "generation",
  1400. duration_ms: "60",
  1401. generation_tail_finalize_ms: "",
  1402. }),
  1403. );
  1404. });
  1405. it("does not count parented agent chunks as generation steps", () => {
  1406. queuePromptTelemetry({
  1407. workspacePath: "/tmp/workspace-parented-agent-chunk",
  1408. taskId: "task-parented-agent-chunk",
  1409. messageId: "message-parented-agent-chunk",
  1410. sendTime: 100,
  1411. });
  1412. activatePromptTelemetry("task-parented-agent-chunk", "message-parented-agent-chunk");
  1413. recordAgentStepTelemetryEvent({
  1414. taskId: "task-parented-agent-chunk",
  1415. event: {
  1416. type: "tool_call",
  1417. taskId: "task-parented-agent-chunk",
  1418. traceId: "trace-parented-agent-chunk",
  1419. toolId: "tool-parent-agent",
  1420. kind: "agent",
  1421. toolName: "Task",
  1422. title: "Task",
  1423. input: {},
  1424. raw: {},
  1425. },
  1426. now: 150,
  1427. });
  1428. expect(
  1429. recordAgentStepTelemetryEvent({
  1430. taskId: "task-parented-agent-chunk",
  1431. event: {
  1432. type: "agent_message_chunk",
  1433. taskId: "task-parented-agent-chunk",
  1434. traceId: "trace-parented-agent-chunk",
  1435. parentToolUseId: "tool-parent-agent",
  1436. content: "subagent output",
  1437. },
  1438. now: 200,
  1439. }),
  1440. ).toEqual([]);
  1441. const finalized = recordAgentStepTelemetryEvent({
  1442. taskId: "task-parented-agent-chunk",
  1443. event: {
  1444. type: "task_complete",
  1445. taskId: "task-parented-agent-chunk",
  1446. traceId: "trace-parented-agent-chunk",
  1447. stopReason: "stop",
  1448. },
  1449. now: 260,
  1450. });
  1451. expect(finalized).toHaveLength(1);
  1452. expect(finalized[0]?.eventExtraDetail).toEqual(
  1453. expect.objectContaining({
  1454. step_type: "tool_call",
  1455. tool_call_id: "tool-parent-agent",
  1456. generation_tail_finalize_ms: "",
  1457. }),
  1458. );
  1459. });
  1460. it("attributes permission waiting to the tool step while keeping wall-clock durations", () => {
  1461. queuePromptTelemetry({
  1462. workspacePath: "/tmp/workspace-permission",
  1463. taskId: "task-permission",
  1464. messageId: "message-permission",
  1465. sendTime: 100,
  1466. });
  1467. activatePromptTelemetry("task-permission", "message-permission");
  1468. recordAgentStepTelemetryEvent({
  1469. taskId: "task-permission",
  1470. event: {
  1471. type: "tool_call",
  1472. taskId: "task-permission",
  1473. traceId: "trace-permission",
  1474. toolId: "tool-permission",
  1475. kind: "bash",
  1476. toolName: "bash",
  1477. title: "Run command",
  1478. input: {},
  1479. raw: {},
  1480. },
  1481. now: 200,
  1482. });
  1483. recordPromptPermissionRequest({
  1484. taskId: "task-permission",
  1485. requestId: "request-permission",
  1486. toolCallId: "tool-permission",
  1487. now: 250,
  1488. });
  1489. // replay/重复投递不能重置等待起点
  1490. recordPromptPermissionRequest({
  1491. taskId: "task-permission",
  1492. requestId: "request-permission",
  1493. toolCallId: "tool-permission",
  1494. now: 300,
  1495. });
  1496. recordPromptPermissionResponse({
  1497. taskId: "task-permission",
  1498. requestId: "request-permission",
  1499. now: 400,
  1500. });
  1501. // 本地响应与 stream response 都可能触发,第二次必须幂等
  1502. recordPromptPermissionResponse({
  1503. taskId: "task-permission",
  1504. requestId: "request-permission",
  1505. now: 450,
  1506. });
  1507. const [toolStep] = recordAgentStepTelemetryEvent({
  1508. taskId: "task-permission",
  1509. event: {
  1510. type: "tool_call_update",
  1511. taskId: "task-permission",
  1512. traceId: "trace-permission",
  1513. toolId: "tool-permission",
  1514. status: "completed",
  1515. kind: "bash",
  1516. toolName: "bash",
  1517. raw: {},
  1518. },
  1519. now: 500,
  1520. });
  1521. const completion = finalizePromptTelemetry({
  1522. taskId: "task-permission",
  1523. status: "success",
  1524. finishedAt: 700,
  1525. });
  1526. expect(toolStep?.eventExtraDetail).toMatchObject({
  1527. step_type: "tool_call",
  1528. duration_ms: "300",
  1529. waiting_ms: "150",
  1530. });
  1531. expect(completion?.eventExtraDetail).toMatchObject({
  1532. duration_ms: "600",
  1533. waiting_ms: "150",
  1534. });
  1535. });
  1536. it("sums permission waits from multiple tool calls into message completion", () => {
  1537. queuePromptTelemetry({
  1538. workspacePath: "/tmp/workspace-permission-sum",
  1539. taskId: "task-permission-sum",
  1540. messageId: "message-permission-sum",
  1541. sendTime: 100,
  1542. });
  1543. activatePromptTelemetry("task-permission-sum", "message-permission-sum");
  1544. const runTool = (
  1545. toolId: string,
  1546. requestId: string,
  1547. startedAt: number,
  1548. requestedAt: number,
  1549. respondedAt: number,
  1550. finishedAt: number,
  1551. ) => {
  1552. recordAgentStepTelemetryEvent({
  1553. taskId: "task-permission-sum",
  1554. event: {
  1555. type: "tool_call",
  1556. taskId: "task-permission-sum",
  1557. traceId: "trace-permission-sum",
  1558. toolId,
  1559. kind: "bash",
  1560. toolName: "bash",
  1561. title: "Run command",
  1562. input: {},
  1563. raw: {},
  1564. },
  1565. now: startedAt,
  1566. });
  1567. recordPromptPermissionRequest({
  1568. taskId: "task-permission-sum",
  1569. requestId,
  1570. toolCallId: toolId,
  1571. now: requestedAt,
  1572. });
  1573. recordPromptPermissionResponse({
  1574. taskId: "task-permission-sum",
  1575. requestId,
  1576. now: respondedAt,
  1577. });
  1578. return recordAgentStepTelemetryEvent({
  1579. taskId: "task-permission-sum",
  1580. event: {
  1581. type: "tool_call_update",
  1582. taskId: "task-permission-sum",
  1583. traceId: "trace-permission-sum",
  1584. toolId,
  1585. status: "completed",
  1586. kind: "bash",
  1587. toolName: "bash",
  1588. raw: {},
  1589. },
  1590. now: finishedAt,
  1591. })[0];
  1592. };
  1593. const firstTool = runTool("tool-1", "request-1", 150, 200, 250, 300);
  1594. const secondTool = runTool("tool-2", "request-2", 350, 400, 550, 600);
  1595. const completion = finalizePromptTelemetry({
  1596. taskId: "task-permission-sum",
  1597. status: "success",
  1598. finishedAt: 700,
  1599. });
  1600. expect(firstTool?.eventExtraDetail.waiting_ms).toBe("50");
  1601. expect(secondTool?.eventExtraDetail.waiting_ms).toBe("150");
  1602. expect(completion?.eventExtraDetail).toMatchObject({
  1603. duration_ms: "600",
  1604. waiting_ms: "200",
  1605. });
  1606. });
  1607. it("accumulates repeated waits on one tool without attributing unmatched waits to it", () => {
  1608. queuePromptTelemetry({
  1609. workspacePath: "/tmp/workspace-permission-repeat",
  1610. taskId: "task-permission-repeat",
  1611. messageId: "message-permission-repeat",
  1612. sendTime: 100,
  1613. });
  1614. activatePromptTelemetry("task-permission-repeat", "message-permission-repeat");
  1615. recordAgentStepTelemetryEvent({
  1616. taskId: "task-permission-repeat",
  1617. event: {
  1618. type: "tool_call",
  1619. taskId: "task-permission-repeat",
  1620. traceId: "trace-permission-repeat",
  1621. toolId: "tool-permission-repeat",
  1622. kind: "bash",
  1623. toolName: "bash",
  1624. title: "Run command",
  1625. input: {},
  1626. raw: {},
  1627. },
  1628. now: 150,
  1629. });
  1630. recordPromptPermissionRequest({
  1631. taskId: "task-permission-repeat",
  1632. requestId: "request-repeat-1",
  1633. toolCallId: "tool-permission-repeat",
  1634. now: 200,
  1635. });
  1636. recordPromptPermissionResponse({
  1637. taskId: "task-permission-repeat",
  1638. requestId: "request-repeat-1",
  1639. now: 250,
  1640. });
  1641. recordPromptPermissionRequest({
  1642. taskId: "task-permission-repeat",
  1643. requestId: "request-repeat-2",
  1644. toolCallId: "tool-permission-repeat",
  1645. now: 300,
  1646. });
  1647. recordPromptPermissionResponse({
  1648. taskId: "task-permission-repeat",
  1649. requestId: "request-repeat-2",
  1650. now: 400,
  1651. });
  1652. recordPromptPermissionRequest({
  1653. taskId: "task-permission-repeat",
  1654. requestId: "request-unmatched",
  1655. toolCallId: "another-tool",
  1656. now: 410,
  1657. });
  1658. recordPromptPermissionResponse({
  1659. taskId: "task-permission-repeat",
  1660. requestId: "request-unmatched",
  1661. now: 460,
  1662. });
  1663. const [toolStep] = recordAgentStepTelemetryEvent({
  1664. taskId: "task-permission-repeat",
  1665. event: {
  1666. type: "tool_call_update",
  1667. taskId: "task-permission-repeat",
  1668. traceId: "trace-permission-repeat",
  1669. toolId: "tool-permission-repeat",
  1670. status: "completed",
  1671. kind: "bash",
  1672. toolName: "bash",
  1673. raw: {},
  1674. },
  1675. now: 500,
  1676. });
  1677. const completion = finalizePromptTelemetry({
  1678. taskId: "task-permission-repeat",
  1679. status: "success",
  1680. finishedAt: 600,
  1681. });
  1682. expect(toolStep?.eventExtraDetail.waiting_ms).toBe("150");
  1683. expect(completion?.eventExtraDetail.waiting_ms).toBe("200");
  1684. });
  1685. it("settles unanswered permission waits when the task terminates", () => {
  1686. queuePromptTelemetry({
  1687. workspacePath: "/tmp/workspace-permission-stop",
  1688. taskId: "task-permission-stop",
  1689. messageId: "message-permission-stop",
  1690. sendTime: 100,
  1691. });
  1692. activatePromptTelemetry("task-permission-stop", "message-permission-stop");
  1693. recordAgentStepTelemetryEvent({
  1694. taskId: "task-permission-stop",
  1695. event: {
  1696. type: "tool_call",
  1697. taskId: "task-permission-stop",
  1698. traceId: "trace-permission-stop",
  1699. toolId: "tool-permission-stop",
  1700. kind: "bash",
  1701. toolName: "bash",
  1702. title: "Run command",
  1703. input: {},
  1704. raw: {},
  1705. },
  1706. now: 200,
  1707. });
  1708. recordPromptPermissionRequest({
  1709. taskId: "task-permission-stop",
  1710. requestId: "request-permission-stop",
  1711. toolCallId: "tool-permission-stop",
  1712. now: 300,
  1713. });
  1714. const [toolStep] = recordAgentStepTelemetryEvent({
  1715. taskId: "task-permission-stop",
  1716. event: {
  1717. type: "task_error",
  1718. taskId: "task-permission-stop",
  1719. traceId: "trace-permission-stop",
  1720. code: "USER_INTERRUPT",
  1721. error: "stopped",
  1722. },
  1723. now: 600,
  1724. });
  1725. const completion = finalizePromptTelemetry({
  1726. taskId: "task-permission-stop",
  1727. status: "user_interrupt",
  1728. finishedAt: 600,
  1729. });
  1730. expect(toolStep?.eventExtraDetail).toMatchObject({
  1731. step_type: "tool_call",
  1732. duration_ms: "400",
  1733. waiting_ms: "300",
  1734. status: "fail",
  1735. });
  1736. expect(completion?.eventExtraDetail).toMatchObject({
  1737. duration_ms: "500",
  1738. waiting_ms: "300",
  1739. });
  1740. });
  1741. it("restores settled permission waiting when terminal tool update has no opening tool call", () => {
  1742. queuePromptTelemetry({
  1743. workspacePath: "/tmp/workspace-permission-replay-settled",
  1744. taskId: "task-permission-replay-settled",
  1745. messageId: "message-permission-replay-settled",
  1746. sendTime: 100,
  1747. });
  1748. activatePromptTelemetry("task-permission-replay-settled", "message-permission-replay-settled");
  1749. recordPromptPermissionRequest({
  1750. taskId: "task-permission-replay-settled",
  1751. requestId: "request-permission-replay-settled",
  1752. toolCallId: "tool-permission-replay-settled",
  1753. now: 200,
  1754. });
  1755. recordPromptPermissionRequest({
  1756. taskId: "task-permission-replay-settled",
  1757. requestId: "request-permission-replay-overlap",
  1758. toolCallId: "tool-permission-replay-settled",
  1759. now: 250,
  1760. });
  1761. recordPromptPermissionResponse({
  1762. taskId: "task-permission-replay-settled",
  1763. requestId: "request-permission-replay-settled",
  1764. now: 350,
  1765. });
  1766. recordPromptPermissionResponse({
  1767. taskId: "task-permission-replay-settled",
  1768. requestId: "request-permission-replay-overlap",
  1769. now: 450,
  1770. });
  1771. const [toolStep] = recordAgentStepTelemetryEvent({
  1772. taskId: "task-permission-replay-settled",
  1773. event: {
  1774. type: "tool_call_update",
  1775. taskId: "task-permission-replay-settled",
  1776. traceId: "trace-permission-replay-settled",
  1777. toolId: "tool-permission-replay-settled",
  1778. status: "completed",
  1779. kind: "bash",
  1780. toolName: "bash",
  1781. raw: {},
  1782. },
  1783. now: 500,
  1784. });
  1785. const completion = finalizePromptTelemetry({
  1786. taskId: "task-permission-replay-settled",
  1787. status: "success",
  1788. finishedAt: 600,
  1789. });
  1790. expect(toolStep?.eventExtraDetail).toMatchObject({
  1791. step_type: "tool_call",
  1792. duration_ms: "350",
  1793. waiting_ms: "350",
  1794. });
  1795. expect(completion?.eventExtraDetail).toMatchObject({
  1796. duration_ms: "500",
  1797. waiting_ms: "350",
  1798. });
  1799. });
  1800. it("uses the pending request time when terminal tool update settles an unanswered wait", () => {
  1801. queuePromptTelemetry({
  1802. workspacePath: "/tmp/workspace-permission-replay-open",
  1803. taskId: "task-permission-replay-open",
  1804. messageId: "message-permission-replay-open",
  1805. sendTime: 100,
  1806. });
  1807. activatePromptTelemetry("task-permission-replay-open", "message-permission-replay-open");
  1808. recordPromptPermissionRequest({
  1809. taskId: "task-permission-replay-open",
  1810. requestId: "request-permission-replay-open",
  1811. toolCallId: "tool-permission-replay-open",
  1812. now: 200,
  1813. });
  1814. const [toolStep] = recordAgentStepTelemetryEvent({
  1815. taskId: "task-permission-replay-open",
  1816. event: {
  1817. type: "tool_call_update",
  1818. taskId: "task-permission-replay-open",
  1819. traceId: "trace-permission-replay-open",
  1820. toolId: "tool-permission-replay-open",
  1821. status: "failed",
  1822. kind: "bash",
  1823. toolName: "bash",
  1824. error: "stopped before permission response",
  1825. raw: {},
  1826. },
  1827. now: 500,
  1828. });
  1829. const completion = finalizePromptTelemetry({
  1830. taskId: "task-permission-replay-open",
  1831. status: "user_interrupt",
  1832. finishedAt: 500,
  1833. });
  1834. expect(toolStep?.eventExtraDetail).toMatchObject({
  1835. step_type: "tool_call",
  1836. duration_ms: "300",
  1837. waiting_ms: "300",
  1838. status: "fail",
  1839. });
  1840. expect(completion?.eventExtraDetail).toMatchObject({
  1841. duration_ms: "400",
  1842. waiting_ms: "300",
  1843. });
  1844. });
  1845. it("uses actual model request fields for agent_step telemetry", () => {
  1846. queuePromptTelemetry({
  1847. workspacePath: "/tmp/workspace-step-model",
  1848. taskId: "task-step-model",
  1849. messageId: "message-step-model",
  1850. inputId: "input-step-model",
  1851. sendTime: 100,
  1852. extraDetail: {
  1853. model_name: "account:bigmodel-start-plan/GLM-5.2",
  1854. model_provider: "provider-custom",
  1855. },
  1856. });
  1857. activatePromptTelemetry("task-step-model", "message-step-model");
  1858. recordPromptModelRequestStarted("task-step-model", {
  1859. type: "task_network_debug_status",
  1860. taskId: "task-step-model",
  1861. traceId: "trace-step-model",
  1862. inputId: "input-step-model",
  1863. eventKey: "event-step-model",
  1864. statusType: "model_request_started",
  1865. requestId: "request-step-model",
  1866. providerId: "provider-custom",
  1867. modelId: "GLM-5.2",
  1868. requestHeaders: {},
  1869. responseHeaders: {},
  1870. requestHeaderCount: 0,
  1871. responseHeaderCount: 0,
  1872. });
  1873. recordAgentStepTelemetryEvent({
  1874. taskId: "task-step-model",
  1875. event: {
  1876. type: "agent_thought_chunk",
  1877. taskId: "task-step-model",
  1878. traceId: "trace-step-model",
  1879. content: "thinking",
  1880. },
  1881. now: 110,
  1882. });
  1883. const [reasoningStep] = recordAgentStepTelemetryEvent({
  1884. taskId: "task-step-model",
  1885. event: {
  1886. type: "agent_message_chunk",
  1887. taskId: "task-step-model",
  1888. traceId: "trace-step-model",
  1889. content: "done",
  1890. },
  1891. now: 150,
  1892. });
  1893. recordPromptTokenUsageDelta({
  1894. taskId: "task-step-model",
  1895. eventKey: "usage-step-model",
  1896. requestId: "request-step-model",
  1897. modelName: "provider-custom/GLM-5.2",
  1898. modelProvider: "provider-custom",
  1899. providerName: "runtime.example.com",
  1900. usage: {
  1901. inputTokens: 80,
  1902. outputTokens: 20,
  1903. totalTokens: 100,
  1904. reasoningTokens: 6,
  1905. cachedInputTokens: 30,
  1906. cachedWriteInputTokens: 4,
  1907. },
  1908. });
  1909. const [generationStep] = recordAgentStepTelemetryEvent({
  1910. taskId: "task-step-model",
  1911. event: {
  1912. type: "task_complete",
  1913. taskId: "task-step-model",
  1914. traceId: "trace-step-model-complete",
  1915. stopReason: "complete",
  1916. },
  1917. now: 180,
  1918. });
  1919. expect(reasoningStep).toEqual({
  1920. taskId: "task-step-model",
  1921. messageId: "message-step-model",
  1922. eventExtraDetail: expect.objectContaining({
  1923. model_name: "provider-custom/GLM-5.2",
  1924. model_provider: "provider-custom",
  1925. input_tokens: "0",
  1926. total_tokens: "0",
  1927. }),
  1928. });
  1929. expect(generationStep).toEqual({
  1930. taskId: "task-step-model",
  1931. messageId: "message-step-model",
  1932. eventExtraDetail: expect.objectContaining({
  1933. model_name: "provider-custom/GLM-5.2",
  1934. model_provider: "provider-custom",
  1935. provider_name: "runtime.example.com",
  1936. model_request_id: "request-step-model",
  1937. model_request_count: "1",
  1938. token_usage_scope: "model_request",
  1939. input_tokens: "80",
  1940. output_tokens: "20",
  1941. reasoning_tokens: "6",
  1942. cached_tokens: "30",
  1943. cache_write_input_tokens: "4",
  1944. total_tokens: "100",
  1945. }),
  1946. });
  1947. });
  1948. it("attributes foreground subagent usage to its parent Agent tool step", () => {
  1949. queuePromptTelemetry({
  1950. workspacePath: "/tmp/workspace-subagent-step",
  1951. taskId: "task-subagent-step",
  1952. messageId: "message-subagent-step",
  1953. sendTime: 100,
  1954. });
  1955. activatePromptTelemetry("task-subagent-step", "message-subagent-step");
  1956. recordAgentStepTelemetryEvent({
  1957. taskId: "task-subagent-step",
  1958. event: {
  1959. type: "tool_call",
  1960. taskId: "task-subagent-step",
  1961. traceId: "trace-agent-tool",
  1962. toolId: "tool-agent",
  1963. kind: "Agent",
  1964. toolName: "Agent",
  1965. title: "Agent",
  1966. input: {},
  1967. raw: {},
  1968. },
  1969. now: 120,
  1970. });
  1971. recordSubagentToolAttribution({
  1972. taskId: "task-subagent-step",
  1973. toolCallId: "tool-agent",
  1974. requestIds: ["child-request-1", "child-request-2"],
  1975. requestCount: 2,
  1976. modelName: "child-provider/child-model",
  1977. modelProvider: "child-provider",
  1978. providerName: "child.example.com",
  1979. agentId: "agent-child",
  1980. usage: {
  1981. inputTokens: 150,
  1982. outputTokens: 50,
  1983. totalTokens: 200,
  1984. reasoningTokens: 12,
  1985. cachedInputTokens: 40,
  1986. cachedWriteInputTokens: 5,
  1987. },
  1988. });
  1989. expect(
  1990. recordAgentStepTelemetryEvent({
  1991. taskId: "task-subagent-step",
  1992. event: {
  1993. type: "tool_call_update",
  1994. taskId: "task-subagent-step",
  1995. traceId: "trace-agent-tool-complete",
  1996. toolId: "tool-agent",
  1997. status: "completed",
  1998. kind: "Agent",
  1999. toolName: "Agent",
  2000. raw: {},
  2001. },
  2002. now: 220,
  2003. }),
  2004. ).toEqual([
  2005. {
  2006. taskId: "task-subagent-step",
  2007. messageId: "message-subagent-step",
  2008. eventExtraDetail: expect.objectContaining({
  2009. model_name: "child-provider/child-model",
  2010. model_provider: "child-provider",
  2011. provider_name: "child.example.com",
  2012. agent_id: "agent-child",
  2013. model_request_id: "",
  2014. model_request_count: "2",
  2015. token_usage_scope: "subagent_requests",
  2016. input_tokens: "150",
  2017. output_tokens: "50",
  2018. total_tokens: "200",
  2019. }),
  2020. },
  2021. ]);
  2022. });
  2023. it("keeps a direct tool request usage separate from foreground subagent usage", () => {
  2024. queuePromptTelemetry({
  2025. workspacePath: "/tmp/workspace-direct-agent-tool",
  2026. taskId: "task-direct-agent-tool",
  2027. messageId: "message-direct-agent-tool",
  2028. inputId: "input-direct-agent-tool",
  2029. sendTime: 100,
  2030. });
  2031. activatePromptTelemetry("task-direct-agent-tool", "message-direct-agent-tool");
  2032. recordPromptModelRequestStarted("task-direct-agent-tool", {
  2033. type: "task_network_debug_status",
  2034. taskId: "task-direct-agent-tool",
  2035. traceId: "trace-main-request",
  2036. inputId: "input-direct-agent-tool",
  2037. eventKey: "main-request-started",
  2038. statusType: "model_request_started",
  2039. requestId: "main-request",
  2040. providerId: "main-provider",
  2041. modelId: "main-model",
  2042. requestHeaders: {},
  2043. responseHeaders: {},
  2044. requestHeaderCount: 0,
  2045. responseHeaderCount: 0,
  2046. });
  2047. recordPromptTokenUsageDelta({
  2048. taskId: "task-direct-agent-tool",
  2049. eventKey: "main-request-usage",
  2050. requestId: "main-request",
  2051. modelName: "main-provider/main-model",
  2052. modelProvider: "main-provider",
  2053. providerName: "main.example.com",
  2054. usage: {
  2055. inputTokens: 75,
  2056. outputTokens: 25,
  2057. totalTokens: 100,
  2058. },
  2059. });
  2060. const [mainRequestStep] = recordAgentStepTelemetryEvent({
  2061. taskId: "task-direct-agent-tool",
  2062. event: {
  2063. type: "tool_call",
  2064. taskId: "task-direct-agent-tool",
  2065. traceId: "trace-agent-tool",
  2066. toolId: "tool-agent-direct",
  2067. kind: "Agent",
  2068. toolName: "Agent",
  2069. title: "Agent",
  2070. input: {},
  2071. raw: {},
  2072. },
  2073. now: 120,
  2074. });
  2075. recordSubagentToolAttribution({
  2076. taskId: "task-direct-agent-tool",
  2077. toolCallId: "tool-agent-direct",
  2078. requestIds: ["child-request"],
  2079. requestCount: 1,
  2080. modelName: "child-provider/child-model",
  2081. modelProvider: "child-provider",
  2082. providerName: "child.example.com",
  2083. agentId: "agent-child",
  2084. usage: {
  2085. inputTokens: 160,
  2086. outputTokens: 40,
  2087. totalTokens: 200,
  2088. },
  2089. });
  2090. const [childToolStep] = recordAgentStepTelemetryEvent({
  2091. taskId: "task-direct-agent-tool",
  2092. event: {
  2093. type: "tool_call_update",
  2094. taskId: "task-direct-agent-tool",
  2095. traceId: "trace-agent-tool-complete",
  2096. toolId: "tool-agent-direct",
  2097. status: "completed",
  2098. kind: "Agent",
  2099. toolName: "Agent",
  2100. raw: {},
  2101. },
  2102. now: 220,
  2103. });
  2104. expect(mainRequestStep?.eventExtraDetail).toMatchObject({
  2105. step_type: "generation",
  2106. model_name: "main-provider/main-model",
  2107. token_usage_scope: "model_request",
  2108. total_tokens: "100",
  2109. });
  2110. expect(childToolStep?.eventExtraDetail).toMatchObject({
  2111. step_type: "tool_call",
  2112. model_name: "child-provider/child-model",
  2113. agent_id: "agent-child",
  2114. token_usage_scope: "subagent_requests",
  2115. total_tokens: "200",
  2116. });
  2117. });
  2118. it("uses the first tool call as time_to_first_token when it arrives before text", () => {
  2119. queuePromptTelemetry({
  2120. workspacePath: "/tmp/workspace-tool-first",
  2121. taskId: "task-tool-first",
  2122. messageId: "message-tool-first",
  2123. sendTime: 100,
  2124. });
  2125. activatePromptTelemetry("task-tool-first", "message-tool-first");
  2126. recordAgentStepTelemetryEvent({
  2127. taskId: "task-tool-first",
  2128. event: {
  2129. type: "tool_call",
  2130. taskId: "task-tool-first",
  2131. traceId: "trace-tool-first",
  2132. toolId: "tool-first",
  2133. kind: "read",
  2134. toolName: "read_file",
  2135. title: "Read file",
  2136. input: {},
  2137. raw: {},
  2138. },
  2139. now: 175,
  2140. });
  2141. expect(
  2142. finalizePromptTelemetry({
  2143. taskId: "task-tool-first",
  2144. status: "success",
  2145. finishedAt: 250,
  2146. })?.eventExtraDetail.time_to_first_token,
  2147. ).toBe("75");
  2148. });
  2149. });
  2150. describe("composeAgentComposition:fg / bg / wf 三维组合", () => {
  2151. it("枚举八个值", async () => {
  2152. const { composeAgentComposition } = await import("@/lib/messageTelemetry.js");
  2153. const compose = (fg: boolean, bg: boolean, wf: boolean) =>
  2154. composeAgentComposition({
  2155. hasForegroundSubagentResult: fg,
  2156. hasBackgroundSubagentResult: bg,
  2157. hasWorkflowResult: wf,
  2158. });
  2159. expect(compose(false, false, false)).toBe("main_only");
  2160. expect(compose(true, false, false)).toBe("main_plus_fg");
  2161. expect(compose(false, true, false)).toBe("main_plus_bg");
  2162. expect(compose(false, false, true)).toBe("main_plus_wf");
  2163. expect(compose(true, true, false)).toBe("main_plus_fg_bg");
  2164. expect(compose(true, false, true)).toBe("main_plus_fg_wf");
  2165. expect(compose(false, true, true)).toBe("main_plus_bg_wf");
  2166. expect(compose(true, true, true)).toBe("main_plus_fg_bg_wf");
  2167. });
  2168. });