v4ConversationTelemetrySupervisor.test.ts 143 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import type { IPlatformService } from "@zcode/shared";
  3. import type { ConversationTelemetryFact } from "@zcode/shared/zcode-protocol-v4";
  4. import { resetMessageTelemetryForTest } from "@/lib/messageTelemetry.js";
  5. import {
  6. clearUiPerfArmsReporterForTest,
  7. setUiPerfArmsReporter,
  8. } from "@/lib/uiPerfArmsTelemetry.js";
  9. import { ConversationTelemetrySupervisor } from "@/v4/telemetry/conversationTelemetrySupervisor.js";
  10. import { buildV4ConversationPromptTelemetryExtraDetail } from "@/v4/telemetry/conversationPromptTelemetry.js";
  11. function createPlatform() {
  12. const reportTelemetryEvent = vi.fn(async () => undefined);
  13. const reportArmsCustomEvent = vi.fn(async () => undefined);
  14. return {
  15. platform: {
  16. reportTelemetryEvent,
  17. reportArmsCustomEvent,
  18. } as unknown as IPlatformService,
  19. reportTelemetryEvent,
  20. reportArmsCustomEvent,
  21. };
  22. }
  23. function commonFact(eventId: string, eventSeq: number, sessionId = "session-1") {
  24. return {
  25. version: 1 as const,
  26. eventId,
  27. eventSeq,
  28. occurredAt: eventSeq,
  29. sessionId,
  30. sourceCommandId: "command-1",
  31. turnId: "turn-1",
  32. };
  33. }
  34. function armsByName(
  35. calls: ReturnType<typeof createPlatform>["reportArmsCustomEvent"],
  36. name: string,
  37. ) {
  38. return calls.mock.calls.map(([payload]) => payload).filter((payload) => payload.name === name);
  39. }
  40. function reportsByElement(
  41. calls: ReturnType<typeof createPlatform>["reportTelemetryEvent"],
  42. elementName: string,
  43. ) {
  44. return calls.mock.calls
  45. .map(([payload]) => payload)
  46. .filter((payload) => payload.elementName === elementName);
  47. }
  48. function startForegroundSubagent(supervisor: ConversationTelemetrySupervisor, sendTime: number) {
  49. supervisor.acceptPromptSeed({
  50. sessionId: "parent-session",
  51. sourceCommandId: "parent-command",
  52. memoryEnabled: true,
  53. sendTime,
  54. extraDetail: {
  55. model_name: "main-provider/main-model",
  56. model_provider: "main-provider",
  57. },
  58. });
  59. supervisor.handleFact({
  60. ...commonFact("parent-turn-start", 1, "parent-session"),
  61. sourceCommandId: "parent-command",
  62. kind: "turn.started",
  63. executionKind: "agent",
  64. });
  65. supervisor.handleFact({
  66. ...commonFact("agent-tool-start", 2, "parent-session"),
  67. sourceCommandId: "parent-command",
  68. kind: "tool.lifecycle",
  69. phase: "started",
  70. toolCallId: "agent-tool",
  71. toolName: "Agent",
  72. });
  73. supervisor.handleFact({
  74. ...commonFact("subagent-spawned", 3, "parent-session"),
  75. sourceCommandId: "parent-command",
  76. kind: "subagent.lifecycle",
  77. phase: "spawned",
  78. agentId: "agent-1",
  79. childSessionId: "child-session",
  80. parentToolCallId: "agent-tool",
  81. background: false,
  82. status: "running",
  83. });
  84. }
  85. function startForegroundSubagentRequest(supervisor: ConversationTelemetrySupervisor) {
  86. supervisor.handleFact({
  87. ...commonFact("child-request-start", 1, "child-session"),
  88. sourceCommandId: "child-command",
  89. turnId: "child-turn",
  90. kind: "model.request.status",
  91. requestId: "child-request",
  92. status: "model_request_started",
  93. providerId: "qwen-provider",
  94. modelId: "qwen3.7-max",
  95. providerHostname: "provider.example.com",
  96. transport: "sse",
  97. querySource: "subagent",
  98. attempt: 1,
  99. maxAttempts: 1,
  100. });
  101. }
  102. function spawnBackgroundSubagent(
  103. supervisor: ConversationTelemetrySupervisor,
  104. input: {
  105. agentId: string;
  106. childSessionId: string;
  107. sourceCommandId?: string;
  108. parentToolCallId?: string;
  109. eventId?: string;
  110. memoryEnabled?: boolean;
  111. },
  112. ) {
  113. supervisor.handleFact({
  114. memoryEnabled: input.memoryEnabled,
  115. ...commonFact(input.eventId ?? `${input.agentId}-spawned`, 1, "parent-session"),
  116. ...(input.sourceCommandId !== undefined
  117. ? { sourceCommandId: input.sourceCommandId }
  118. : { sourceCommandId: "parent-command" }),
  119. kind: "subagent.lifecycle",
  120. phase: "spawned",
  121. agentId: input.agentId,
  122. childSessionId: input.childSessionId,
  123. parentToolCallId: input.parentToolCallId ?? `${input.agentId}-parent-tool`,
  124. background: true,
  125. status: "running",
  126. });
  127. }
  128. function reportForegroundSubagentUsage(supervisor: ConversationTelemetrySupervisor) {
  129. supervisor.handleFact({
  130. ...commonFact("child-usage", 2, "child-session"),
  131. sourceCommandId: "child-command",
  132. turnId: "child-turn",
  133. kind: "usage.delta",
  134. requestId: "child-request",
  135. providerId: "qwen-provider",
  136. modelId: "qwen3.7-max",
  137. providerHostname: "provider.example.com",
  138. inputTokens: 8_616,
  139. outputTokens: 69,
  140. totalTokens: 8_685,
  141. reasoningTokens: 0,
  142. cacheReadTokens: 0,
  143. cacheWriteTokens: 5_797,
  144. });
  145. }
  146. function terminateForegroundSubagentParent(
  147. supervisor: ConversationTelemetrySupervisor,
  148. error?: {
  149. code?: string;
  150. message?: string;
  151. },
  152. ) {
  153. supervisor.handleFact({
  154. ...commonFact("agent-tool-failed", 4, "parent-session"),
  155. sourceCommandId: "parent-command",
  156. kind: "tool.lifecycle",
  157. phase: "failed",
  158. toolCallId: "agent-tool",
  159. toolName: "Agent",
  160. ...(error?.code ? { errorCode: error.code } : {}),
  161. errorMessage:
  162. error?.message ??
  163. "Agent was cancelled before the subagent returned findings or background launch completed",
  164. });
  165. supervisor.handleFact({
  166. ...commonFact("parent-turn-terminal", 5, "parent-session"),
  167. sourceCommandId: "parent-command",
  168. kind: "turn.terminal",
  169. status: "interrupted",
  170. resultType: "cancelled",
  171. });
  172. }
  173. function completionAgentCompositions(
  174. calls: ReturnType<typeof createPlatform>["reportTelemetryEvent"],
  175. ): string[] {
  176. return reportsByElement(calls, "message_completion").map(
  177. (report) => report.eventExtraDetail.agent_composition,
  178. );
  179. }
  180. describe("ConversationTelemetrySupervisor", () => {
  181. it.each([
  182. ["resolved", "completed", "pptx"],
  183. ["unresolved", "failed", "unknown"],
  184. ["legacy", "completed", "unknown"],
  185. ["resolved-failure", "failed", "pptx"],
  186. ["unsafe", "failed", "unknown"],
  187. ["missing-source", "completed", "unknown"],
  188. ] as const)(
  189. "Skill 只接受终态已解析名称,旧调度字段不进入上报:%s",
  190. async (scenario, phase, expected) => {
  191. const { platform, reportTelemetryEvent } = createPlatform();
  192. const supervisor = new ConversationTelemetrySupervisor({
  193. platform,
  194. workspaceScopeKey: "skill-names",
  195. });
  196. supervisor.acceptPromptSeed({
  197. sessionId: "session-1",
  198. sourceCommandId: "command-1",
  199. sendTime: 1,
  200. extraDetail: {},
  201. });
  202. supervisor.handleFact({ ...commonFact("turn-start", 1), kind: "turn.started" });
  203. supervisor.handleFact({
  204. ...commonFact("skill-start", 2),
  205. kind: "tool.lifecycle",
  206. phase: "scheduled",
  207. toolCallId: "skill-tool",
  208. toolName: "Skill",
  209. ...(scenario !== "legacy" ? { skillName: "unverified-request-name" } : {}),
  210. });
  211. supervisor.handleFact({
  212. ...commonFact("skill-end", 3),
  213. kind: "tool.lifecycle",
  214. phase,
  215. toolCallId: "skill-tool",
  216. toolName: "Skill",
  217. ...(scenario === "resolved" || scenario === "resolved-failure"
  218. ? { skillName: "pptx", skillSource: "plugin", skillPluginId: "document-skills@market" }
  219. : scenario === "unsafe"
  220. ? { skillName: "/Users/FAKE_USER/private", skillSource: "zcode" }
  221. : scenario === "missing-source"
  222. ? { skillName: "unverified-name" }
  223. : {}),
  224. });
  225. await supervisor.flushReportsForTest();
  226. const steps = reportsByElement(reportTelemetryEvent, "agent_step");
  227. expect(steps).toHaveLength(1);
  228. expect(steps[0].eventExtraDetail.skill_name).toBe(expected);
  229. supervisor.dispose();
  230. },
  231. );
  232. it("父 ACK 未到时 child step 从启动事实读取 Memory", async () => {
  233. const { platform, reportTelemetryEvent } = createPlatform();
  234. const supervisor = new ConversationTelemetrySupervisor({
  235. platform,
  236. workspaceScopeKey: "memory-child-before-ack",
  237. });
  238. spawnBackgroundSubagent(supervisor, {
  239. agentId: "memory-child",
  240. childSessionId: "child-session",
  241. memoryEnabled: true,
  242. });
  243. supervisor.handleFact({
  244. ...commonFact("child-tool", 2, "child-session"),
  245. kind: "tool.lifecycle",
  246. phase: "started",
  247. toolCallId: "read-1",
  248. toolName: "Read",
  249. });
  250. supervisor.handleFact({
  251. ...commonFact("child-tool-end", 3, "child-session"),
  252. kind: "tool.lifecycle",
  253. phase: "completed",
  254. toolCallId: "read-1",
  255. toolName: "Read",
  256. });
  257. await supervisor.flushReportsForTest();
  258. const steps = reportsByElement(reportTelemetryEvent, "agent_step");
  259. expect(steps).toHaveLength(1);
  260. expect(steps[0].eventExtraDetail.memory_enabled).toBe("1");
  261. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(0);
  262. supervisor.dispose();
  263. });
  264. it.each([true, false, undefined])(
  265. "Memory 开关 %s 在三事件保持一致且不读取可变设置",
  266. async (memoryEnabled) => {
  267. const { platform, reportTelemetryEvent } = createPlatform();
  268. const supervisor = new ConversationTelemetrySupervisor({
  269. platform,
  270. workspaceScopeKey: "memory-test",
  271. });
  272. const seed = {
  273. sessionId: "session-1",
  274. sourceCommandId: "command-1",
  275. sendTime: 1,
  276. memoryEnabled,
  277. extraDetail: {},
  278. };
  279. // 事实可能先于 ACK 到达,必须复用既有缓冲顺序。
  280. supervisor.handleFact({
  281. ...commonFact("memory-start", 1),
  282. kind: "turn.started",
  283. memoryEnabled,
  284. });
  285. supervisor.acceptPromptSeed(seed);
  286. seed.memoryEnabled = !memoryEnabled;
  287. supervisor.handleFact({
  288. ...commonFact("memory-tool", 2),
  289. kind: "tool.lifecycle",
  290. phase: "started",
  291. toolCallId: "read-1",
  292. toolName: "Read",
  293. });
  294. supervisor.handleFact({
  295. ...commonFact("memory-tool-end", 3),
  296. kind: "tool.lifecycle",
  297. phase: "completed",
  298. toolCallId: "read-1",
  299. toolName: "Read",
  300. });
  301. supervisor.handleFact({
  302. ...commonFact("memory-end", 4),
  303. kind: "turn.terminal",
  304. status: "success",
  305. resultType: "success",
  306. });
  307. supervisor.acceptPromptSeed(seed);
  308. await vi.waitFor(() =>
  309. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(1),
  310. );
  311. for (const name of ["send_btn", "message_completion", "agent_step"]) {
  312. const reports = reportsByElement(reportTelemetryEvent, name);
  313. expect(reports).toHaveLength(1);
  314. expect(reports[0].eventExtraDetail.memory_enabled).toBe(
  315. memoryEnabled === undefined ? "" : memoryEnabled ? "1" : "0",
  316. );
  317. }
  318. supervisor.dispose();
  319. },
  320. );
  321. it.each([true, false])(
  322. "后台轮从 live fact 继承 Memory %s 且不伪造 send_btn",
  323. async (memoryEnabled) => {
  324. const { platform, reportTelemetryEvent } = createPlatform();
  325. const supervisor = new ConversationTelemetrySupervisor({
  326. platform,
  327. workspaceScopeKey: "memory-background",
  328. });
  329. supervisor.handleFact({
  330. ...commonFact("bg-start", 1),
  331. kind: "turn.started",
  332. inputSource: "background_task",
  333. memoryEnabled,
  334. });
  335. supervisor.handleFact({
  336. ...commonFact("bg-end", 2),
  337. kind: "turn.terminal",
  338. status: "success",
  339. resultType: "success",
  340. });
  341. await vi.waitFor(() =>
  342. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(1),
  343. );
  344. expect(reportsByElement(reportTelemetryEvent, "send_btn")).toHaveLength(0);
  345. expect(
  346. reportsByElement(reportTelemetryEvent, "message_completion")[0].eventExtraDetail
  347. .memory_enabled,
  348. ).toBe(memoryEnabled ? "1" : "0");
  349. supervisor.dispose();
  350. },
  351. );
  352. it.each(["zai", "bigmodel"])(
  353. "%s 新旧身份在实际请求换模后的完成/step 上报对齐",
  354. async (family) => {
  355. const run = async (modern: boolean) => {
  356. resetMessageTelemetryForTest();
  357. const { platform, reportTelemetryEvent, reportArmsCustomEvent } = createPlatform();
  358. // perf_ui_* 走模块级 reporter,与 plan_* 直接经 platform 上报不同,需显式挂载才能观察到。
  359. setUiPerfArmsReporter(platform);
  360. let now = 100;
  361. const supervisor = new ConversationTelemetrySupervisor({
  362. platform,
  363. workspaceScopeKey: "compat-workspace",
  364. now: () => now,
  365. });
  366. const detach = supervisor.attachForeground({}, "session-1");
  367. const team = modern
  368. ? `account:${family}-team-coding-plan`
  369. : `builtin:${family}-coding-plan`;
  370. const start = modern ? `account:${family}-start-plan` : `builtin:${family}-start-plan`;
  371. supervisor.acceptPromptSeed({
  372. sessionId: "session-1",
  373. sourceCommandId: "command-1",
  374. sendTime: now,
  375. extraDetail: buildV4ConversationPromptTelemetryExtraDetail({
  376. configProvider: team,
  377. modelName: "GLM-5.3",
  378. providerBaseURL: "https://example.com/api",
  379. planIdentitySnapshot: {
  380. generatedAt: 1,
  381. planStatus: "coding_plan",
  382. planProductId: "team",
  383. },
  384. }),
  385. });
  386. supervisor.handleFact({
  387. ...commonFact("start", 1),
  388. kind: "turn.started",
  389. executionKind: "agent",
  390. });
  391. let seq = 2;
  392. for (const providerId of [team, start]) {
  393. now += 10;
  394. const requestId = `request-${seq}`;
  395. const fact = Object.freeze({
  396. // plan_request 按 eventId 在模块级去重且跨用例保留;family/run 前缀保证每轮都能观察到上报。
  397. ...commonFact(`${family}-${modern ? "modern" : "legacy"}-request-${seq}`, seq++),
  398. kind: "model.request.status" as const,
  399. requestId,
  400. status: "model_request_started" as const,
  401. providerId,
  402. modelId: "GLM-5.3",
  403. providerHostname: "example.com",
  404. transport: "fetch" as const,
  405. querySource: "build",
  406. attempt: 1,
  407. maxAttempts: 1,
  408. });
  409. supervisor.handleFact(fact);
  410. supervisor.handleFact({
  411. ...commonFact(`chunk-${seq}`, seq++),
  412. kind: "stream.chunk",
  413. channel: "text",
  414. chunkLength: 5,
  415. firstChunk: true,
  416. });
  417. supervisor.handleFact({
  418. ...commonFact(`usage-${seq}`, seq++),
  419. kind: "usage.delta",
  420. requestId,
  421. providerId,
  422. modelId: "GLM-5.3",
  423. providerHostname: "example.com",
  424. inputTokens: 10,
  425. outputTokens: 5,
  426. totalTokens: 15,
  427. });
  428. supervisor.handleFact({
  429. ...commonFact(`tool-${seq}`, seq++),
  430. kind: "tool.lifecycle",
  431. phase: "started",
  432. toolCallId: requestId,
  433. toolName: "Read",
  434. });
  435. supervisor.handleFact({
  436. ...commonFact(`end-${seq}`, seq++),
  437. kind: "tool.lifecycle",
  438. phase: "completed",
  439. toolCallId: requestId,
  440. toolName: "Read",
  441. });
  442. }
  443. now += 10;
  444. const terminal = {
  445. ...commonFact("terminal", seq++),
  446. kind: "turn.terminal" as const,
  447. status: "success" as const,
  448. resultType: "complete" as const,
  449. };
  450. supervisor.handleFact(terminal);
  451. supervisor.handleFact(terminal);
  452. await supervisor.flushReportsForTest();
  453. const reports = reportTelemetryEvent.mock.calls.map(([payload]) => ({
  454. element: payload.elementName,
  455. talkId: payload.talkId,
  456. messageId: payload.messageId,
  457. // step_id 是每次采集随机生成值,不是统计维度;其他字段完整成对比较。
  458. detail: Object.fromEntries(
  459. Object.entries(payload.eventExtraDetail).filter(([key]) => key !== "step_id"),
  460. ),
  461. }));
  462. expect(reports.filter((event) => event.element === "message_completion")).toHaveLength(1);
  463. expect(
  464. reports.find((event) => event.element === "message_completion")?.detail,
  465. ).toMatchObject({
  466. model_provider: `builtin:${family}-start-plan`,
  467. model_name: `builtin:${family}-start-plan/GLM-5.3`,
  468. input_tokens: "20",
  469. output_tokens: "10",
  470. });
  471. expect(
  472. reports
  473. .filter((event) => event.element === "agent_step")
  474. .map((event) => event.detail.model_provider),
  475. ).toEqual(
  476. expect.arrayContaining([`builtin:${family}-coding-plan`, `builtin:${family}-start-plan`]),
  477. );
  478. // ARMS 侧复用同一份 legacy detail:内置 provider 的旧报表身份必须保留、模型按白名单规范化,
  479. // 否则内置用户在 plan_ttft / perf_ui_* 看板里会整体落入 custom。
  480. expect(armsByName(reportArmsCustomEvent, "plan_ttft")[0]?.properties).toMatchObject({
  481. provider_id: `builtin:${family}-start-plan`,
  482. provider_scope: "builtin",
  483. model_name: "glm-5.3",
  484. });
  485. expect(armsByName(reportArmsCustomEvent, "perf_ui_first_token")[0]?.properties?.model).toBe(
  486. "glm-5.3",
  487. );
  488. // plan_request 直接使用协议事件里的 provider(account:* 或旧 builtin:*),两种命名空间都应保留。
  489. const planRequests = armsByName(reportArmsCustomEvent, "plan_request");
  490. expect(planRequests.map((payload) => payload.properties?.provider_id)).toEqual([
  491. team,
  492. start,
  493. ]);
  494. for (const payload of planRequests) {
  495. expect(payload.properties).toMatchObject({
  496. provider_scope: "builtin",
  497. model_name: "glm-5.3",
  498. });
  499. }
  500. detach();
  501. supervisor.dispose();
  502. return reports;
  503. };
  504. expect(await run(true)).toEqual(await run(false));
  505. },
  506. );
  507. beforeEach(() => {
  508. resetMessageTelemetryForTest();
  509. clearUiPerfArmsReporterForTest();
  510. });
  511. afterEach(() => {
  512. clearUiPerfArmsReporterForTest();
  513. resetMessageTelemetryForTest();
  514. });
  515. it("send seed 以 V4 config provider 为 model_provider,并保留旧 model value 与 agent 口径", () => {
  516. expect(
  517. buildV4ConversationPromptTelemetryExtraDetail({
  518. agentProvider: "glm",
  519. configProvider: "custom-provider-id",
  520. modelName: "custom-model",
  521. askMode: "plan",
  522. providerBaseURL: "https://api.example.com/v1/messages?token=secret",
  523. planIdentitySnapshot: {
  524. generatedAt: 123,
  525. planStatus: "coding_plan",
  526. planProductId: "product-1",
  527. },
  528. }),
  529. ).toEqual({
  530. ask_mode: "plan",
  531. model_name: "custom:custom-provider-id:custom-model",
  532. model_provider: "custom-provider-id",
  533. provider_name: "api.example.com",
  534. agent: "glm",
  535. plan_status: "coding_plan",
  536. plan_product_id: "product-1",
  537. message_source: "chat",
  538. task_trigger: "",
  539. });
  540. });
  541. it("send seed 缺少显式运行时 provider 时沿用 ZCode Agent 默认值", () => {
  542. expect(
  543. buildV4ConversationPromptTelemetryExtraDetail({
  544. configProvider: "glm",
  545. modelName: "glm-model",
  546. askMode: "build",
  547. }),
  548. ).toMatchObject({
  549. agent: "glm",
  550. message_source: "chat",
  551. model_name: "glm-model",
  552. model_provider: "glm",
  553. task_trigger: "",
  554. });
  555. });
  556. it("沿用旧 payload 收口 send/completion/step 与 foreground ARMS", async () => {
  557. const { platform, reportTelemetryEvent, reportArmsCustomEvent } = createPlatform();
  558. setUiPerfArmsReporter(platform);
  559. let now = 100;
  560. const supervisor = new ConversationTelemetrySupervisor({
  561. platform,
  562. workspaceScopeKey: "base\u0000workspace\u00001",
  563. now: () => now,
  564. });
  565. const detach = supervisor.attachForeground({}, "session-1");
  566. supervisor.recordComposerFocus();
  567. now = 120;
  568. supervisor.recordComposerTextChange("hello");
  569. now = 200;
  570. supervisor.acceptPromptSeed({
  571. sessionId: "session-1",
  572. sourceCommandId: "command-1",
  573. sendTime: now,
  574. extraDetail: {
  575. ask_mode: "build",
  576. model_name: "seed-model",
  577. model_provider: "seed-provider",
  578. agent: "glm",
  579. plan_status: "unknown",
  580. plan_product_id: "",
  581. },
  582. });
  583. const send = reportsByElement(reportTelemetryEvent, "send_btn");
  584. expect(send).toHaveLength(1);
  585. expect(send[0]).toMatchObject({
  586. elementName: "send_btn",
  587. eventRegion: "app",
  588. eventType: "ck",
  589. talkId: "session-1",
  590. messageId: "command-1",
  591. eventExtraDetail: {
  592. ask_mode: "build",
  593. model_name: "seed-model",
  594. model_provider: "seed-provider",
  595. agent: "glm",
  596. plan_status: "unknown",
  597. plan_product_id: "",
  598. input_start_time: "100",
  599. input_first_char_time: "120",
  600. input_send_time: "200",
  601. },
  602. });
  603. now = 210;
  604. supervisor.handleFact({
  605. ...commonFact("event-start", 1),
  606. kind: "turn.started",
  607. executionKind: "agent",
  608. });
  609. now = 220;
  610. supervisor.handleFact({
  611. ...commonFact("event-model", 2),
  612. kind: "model.request.status",
  613. requestId: "request-1",
  614. status: "model_request_started",
  615. providerId: "runtime-provider",
  616. modelId: "runtime-model",
  617. providerHostname: "runtime.example.com",
  618. transport: "fetch",
  619. querySource: "build",
  620. attempt: 1,
  621. maxAttempts: 3,
  622. });
  623. now = 250;
  624. supervisor.handleFact({
  625. ...commonFact("event-thought", 3),
  626. kind: "stream.chunk",
  627. channel: "thought",
  628. chunkLength: 10,
  629. firstChunk: true,
  630. });
  631. now = 260;
  632. supervisor.handleFact({
  633. ...commonFact("event-permission-request", 4),
  634. kind: "permission.lifecycle",
  635. phase: "requested",
  636. requestId: "permission-1",
  637. toolCallId: "tool-1",
  638. toolName: "bash",
  639. });
  640. now = 300;
  641. supervisor.handleFact({
  642. ...commonFact("event-tool-start", 5),
  643. kind: "tool.lifecycle",
  644. phase: "started",
  645. toolCallId: "tool-1",
  646. toolName: "bash",
  647. });
  648. now = 350;
  649. supervisor.handleFact({
  650. ...commonFact("event-permission-response", 6),
  651. kind: "permission.lifecycle",
  652. phase: "resolved",
  653. requestId: "permission-1",
  654. toolCallId: "tool-1",
  655. toolName: "bash",
  656. decision: "allow",
  657. });
  658. now = 500;
  659. supervisor.handleFact({
  660. ...commonFact("event-tool-complete", 7),
  661. kind: "tool.lifecycle",
  662. phase: "completed",
  663. toolCallId: "tool-1",
  664. toolName: "bash",
  665. parentToolCallId: "parent-tool",
  666. childToolCallId: "child-tool",
  667. childSessionId: "child-session",
  668. agentId: "agent-1",
  669. agentType: "subagent",
  670. performance: {
  671. totalMs: 200,
  672. permissionWaitMs: 90,
  673. commandRunMs: 110,
  674. exitCode: 0,
  675. timedOut: false,
  676. outputBytes: 42,
  677. commandCategory: "read",
  678. commandHash: "0123456789abcdef",
  679. workspaceKind: "local",
  680. },
  681. });
  682. now = 600;
  683. supervisor.handleFact({
  684. ...commonFact("event-text-1", 8),
  685. kind: "stream.chunk",
  686. channel: "text",
  687. chunkLength: 3,
  688. firstChunk: false,
  689. assistantMessageId: "assistant-1",
  690. });
  691. now = 3_600;
  692. supervisor.handleFact({
  693. ...commonFact("event-text-2", 9),
  694. kind: "stream.chunk",
  695. channel: "text",
  696. chunkLength: 3,
  697. firstChunk: false,
  698. assistantMessageId: "assistant-1",
  699. });
  700. expect(armsByName(reportArmsCustomEvent, "perf_ui_stream_stall")).toHaveLength(0);
  701. now = 6_601;
  702. supervisor.handleFact({
  703. ...commonFact("event-text-3", 10),
  704. kind: "stream.chunk",
  705. channel: "text",
  706. chunkLength: 3,
  707. firstChunk: false,
  708. assistantMessageId: "assistant-1",
  709. });
  710. expect(armsByName(reportArmsCustomEvent, "perf_ui_stream_stall")).toEqual([
  711. {
  712. name: "perf_ui_stream_stall",
  713. group: "ui_perf",
  714. value: 3001,
  715. properties: {
  716. stall_ms: 3001,
  717. waiting_tool: false,
  718. // `runtime-provider` 不是内置 provider,复合模型值必须归一,避免把自定义
  719. // provider 名与模型名透传到 ARMS。
  720. model: "custom",
  721. chunk_type: "message",
  722. talk_id: "session-1",
  723. message_id: "assistant-1",
  724. },
  725. },
  726. ]);
  727. now = 6_700;
  728. supervisor.handleFact({
  729. ...commonFact("event-usage", 11),
  730. kind: "usage.delta",
  731. inputTokens: 10,
  732. outputTokens: 5,
  733. totalTokens: 18,
  734. reasoningTokens: 3,
  735. cacheReadTokens: 2,
  736. cacheWriteTokens: 1,
  737. });
  738. now = 7_000;
  739. supervisor.handleFact({
  740. ...commonFact("event-terminal", 12),
  741. kind: "turn.terminal",
  742. status: "success",
  743. resultType: "complete",
  744. durationMs: 6_800,
  745. tokenCount: 18,
  746. toolCallCount: 1,
  747. });
  748. await supervisor.flushReportsForTest();
  749. const completion = reportsByElement(reportTelemetryEvent, "message_completion");
  750. expect(completion).toHaveLength(1);
  751. expect(completion[0]).toMatchObject({
  752. elementName: "message_completion",
  753. eventRegion: "app",
  754. eventType: "agent_trace",
  755. talkId: "session-1",
  756. messageId: "command-1",
  757. eventExtraDetail: {
  758. ask_mode: "build",
  759. model_name: "runtime-provider/runtime-model",
  760. model_provider: "runtime-provider",
  761. provider_name: "runtime.example.com",
  762. agent: "glm",
  763. plan_status: "unknown",
  764. plan_product_id: "",
  765. input_tokens: "10",
  766. output_tokens: "5",
  767. reasoning_tokens: "3",
  768. cached_input_tokens: "2",
  769. cache_write_input_tokens: "1",
  770. tool_use_prompt_tokens: "0",
  771. total_tokens: "18",
  772. duration_ms: "6800",
  773. waiting_ms: "90",
  774. generated_code_lines: "0",
  775. file_change_cnt: "0",
  776. time_to_first_token: "50",
  777. request_time: "200",
  778. status: "success",
  779. agent_step_cnt: "3",
  780. retry_cnt: "0",
  781. tool_call_total: "1",
  782. tool_call_failed: "0",
  783. error_type: "",
  784. error_msg: "",
  785. },
  786. });
  787. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(3);
  788. expect(armsByName(reportArmsCustomEvent, "plan_request")).toHaveLength(1);
  789. expect(armsByName(reportArmsCustomEvent, "perf_ui_tool_call_detail")[0]).toMatchObject({
  790. properties: {
  791. tool_call_id: "tool-1",
  792. parent_tool_call_id: "parent-tool",
  793. child_tool_call_id: "child-tool",
  794. child_session_id: "child-session",
  795. agent_id: "agent-1",
  796. agent_type: "subagent",
  797. },
  798. });
  799. expect(armsByName(reportArmsCustomEvent, "perf_ui_first_token")[0]?.value).toBe(50);
  800. expect(armsByName(reportArmsCustomEvent, "plan_ttft")[0]?.value).toBe(50);
  801. expect(armsByName(reportArmsCustomEvent, "perf_ui_message_complete")[0]?.value).toBe(6_800);
  802. expect(armsByName(reportArmsCustomEvent, "perf_ui_turn_breakdown")[0]).toMatchObject({
  803. value: 6_800,
  804. properties: {
  805. waiting_ms: 90,
  806. file_change_cnt: 0,
  807. generated_code_lines: 0,
  808. },
  809. });
  810. detach();
  811. supervisor.dispose();
  812. });
  813. it.each([
  814. {
  815. phase: "completed" as const,
  816. errorMessage: undefined,
  817. expectedStatus: "success",
  818. expectedErrorType: "",
  819. expectedErrorMessage: "",
  820. expectedFailedCount: "0",
  821. },
  822. {
  823. phase: "failed" as const,
  824. errorMessage: "exit 2",
  825. expectedStatus: "fail",
  826. expectedErrorType: "TOOL_EXEC_ERROR",
  827. expectedErrorMessage: "exit 2",
  828. expectedFailedCount: "1",
  829. },
  830. ])(
  831. "工具 $phase terminal 立即收口 /event/report agent_step,不等待 turn terminal",
  832. async ({
  833. phase,
  834. errorMessage,
  835. expectedStatus,
  836. expectedErrorType,
  837. expectedErrorMessage,
  838. expectedFailedCount,
  839. }) => {
  840. const { platform, reportTelemetryEvent } = createPlatform();
  841. let now = 100;
  842. const supervisor = new ConversationTelemetrySupervisor({
  843. platform,
  844. workspaceScopeKey: `scope-tool-terminal-${phase}`,
  845. now: () => now,
  846. });
  847. supervisor.acceptPromptSeed({
  848. sessionId: "session-1",
  849. sourceCommandId: "command-1",
  850. sendTime: now,
  851. extraDetail: { model_name: "model", model_provider: "provider" },
  852. });
  853. now = 120;
  854. supervisor.handleFact({
  855. ...commonFact(`turn-start-${phase}`, 1),
  856. kind: "turn.started",
  857. executionKind: "agent",
  858. });
  859. now = 200;
  860. supervisor.handleFact({
  861. ...commonFact(`tool-start-${phase}`, 2),
  862. kind: "tool.lifecycle",
  863. phase: "started",
  864. toolCallId: "tool-1",
  865. toolName: "Bash",
  866. });
  867. now = 350;
  868. supervisor.handleFact({
  869. ...commonFact(`tool-terminal-${phase}`, 3),
  870. kind: "tool.lifecycle",
  871. phase,
  872. toolCallId: "tool-1",
  873. toolName: "Bash",
  874. ...(errorMessage ? { errorMessage } : {}),
  875. });
  876. await supervisor.flushReportsForTest();
  877. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toEqual([]);
  878. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toEqual([
  879. expect.objectContaining({
  880. elementName: "agent_step",
  881. eventType: "agent_trace",
  882. talkId: "session-1",
  883. messageId: "command-1",
  884. eventExtraDetail: expect.objectContaining({
  885. step_type: "tool_call",
  886. tool_name: "Bash",
  887. tool_call_id: "tool-1",
  888. duration_ms: "150",
  889. status: expectedStatus,
  890. error_type: expectedErrorType,
  891. error_msg: expectedErrorMessage ? "[redacted]" : "",
  892. }),
  893. }),
  894. ]);
  895. now = 900;
  896. supervisor.handleFact({
  897. ...commonFact(`turn-terminal-${phase}`, 4),
  898. kind: "turn.terminal",
  899. status: "success",
  900. resultType: "complete",
  901. });
  902. await supervisor.flushReportsForTest();
  903. expect(
  904. reportTelemetryEvent.mock.calls
  905. .map(([payload]) => payload.elementName)
  906. .filter((name) => name === "agent_step" || name === "message_completion"),
  907. ).toEqual(["agent_step", "message_completion"]);
  908. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toEqual([
  909. expect.objectContaining({
  910. eventExtraDetail: expect.objectContaining({
  911. agent_step_cnt: "1",
  912. tool_call_total: "1",
  913. tool_call_failed: expectedFailedCount,
  914. }),
  915. }),
  916. ]);
  917. supervisor.dispose();
  918. },
  919. );
  920. it.each([
  921. ["main-provider", "child-provider", "main-provider", "child-provider"],
  922. [
  923. "account:bigmodel-team-coding-plan",
  924. "account:zai-start-plan",
  925. "builtin:bigmodel-coding-plan",
  926. "builtin:zai-start-plan",
  927. ],
  928. ])(
  929. "主模型 %s、前台 Subagent %s、后续主模型分别保留 usage 与旧统计身份",
  930. async (mainId, childId, mainReportId, childReportId) => {
  931. const { platform, reportTelemetryEvent } = createPlatform();
  932. let now = 100;
  933. const supervisor = new ConversationTelemetrySupervisor({
  934. platform,
  935. workspaceScopeKey: "scope-foreground-subagent-usage",
  936. now: () => now,
  937. });
  938. supervisor.acceptPromptSeed({
  939. sessionId: "session-1",
  940. sourceCommandId: "command-1",
  941. sendTime: now,
  942. extraDetail: {
  943. model_name: "seed-model",
  944. model_provider: "seed-provider",
  945. },
  946. });
  947. supervisor.handleFact({
  948. ...commonFact("parent-turn-start", 1),
  949. kind: "turn.started",
  950. executionKind: "agent",
  951. });
  952. now = 110;
  953. supervisor.handleFact({
  954. ...commonFact("main-request-1-start", 2),
  955. kind: "model.request.status",
  956. requestId: "main-request-1",
  957. status: "model_request_started",
  958. providerId: mainId,
  959. modelId: "main-model",
  960. providerHostname: "main.example.com",
  961. transport: "sse",
  962. querySource: "main_turn",
  963. attempt: 1,
  964. maxAttempts: 1,
  965. });
  966. now = 120;
  967. supervisor.handleFact({
  968. ...commonFact("main-reasoning", 3),
  969. kind: "stream.chunk",
  970. channel: "thought",
  971. chunkLength: 3,
  972. firstChunk: true,
  973. });
  974. now = 130;
  975. supervisor.handleFact({
  976. ...commonFact("main-generation-1", 4),
  977. kind: "stream.chunk",
  978. channel: "text",
  979. chunkLength: 4,
  980. firstChunk: true,
  981. });
  982. supervisor.handleFact({
  983. ...commonFact("main-usage-1", 5),
  984. kind: "usage.delta",
  985. requestId: "main-request-1",
  986. providerId: mainId,
  987. modelId: "main-model",
  988. providerHostname: "main.example.com",
  989. inputTokens: 80,
  990. outputTokens: 20,
  991. totalTokens: 100,
  992. reasoningTokens: 5,
  993. cacheReadTokens: 10,
  994. cacheWriteTokens: 2,
  995. });
  996. now = 140;
  997. supervisor.handleFact({
  998. ...commonFact("agent-tool-start", 6),
  999. kind: "tool.lifecycle",
  1000. phase: "started",
  1001. toolCallId: "agent-tool-1",
  1002. toolName: "Agent",
  1003. });
  1004. supervisor.handleFact({
  1005. ...commonFact("subagent-spawned", 7),
  1006. kind: "subagent.lifecycle",
  1007. phase: "spawned",
  1008. agentId: "agent-1",
  1009. agentType: "explore",
  1010. childSessionId: "child-session-1",
  1011. parentToolCallId: "agent-tool-1",
  1012. background: false,
  1013. status: "running",
  1014. });
  1015. supervisor.handleFact({
  1016. // detached child 的 eventId 允许与父 session 同号,去重必须带 sessionId。
  1017. ...commonFact("main-request-1-start", 1, "child-session-1"),
  1018. sourceCommandId: "child-command-1",
  1019. turnId: "child-turn-1",
  1020. kind: "model.request.status",
  1021. requestId: "child-request-1",
  1022. status: "model_request_started",
  1023. providerId: childId,
  1024. modelId: "child-model",
  1025. providerHostname: "child.example.com",
  1026. transport: "sse",
  1027. querySource: "subagent",
  1028. attempt: 1,
  1029. maxAttempts: 1,
  1030. });
  1031. supervisor.handleFact({
  1032. ...commonFact("main-usage-1", 2, "child-session-1"),
  1033. sourceCommandId: "child-command-1",
  1034. turnId: "child-turn-1",
  1035. kind: "usage.delta",
  1036. requestId: "child-request-1",
  1037. providerId: childId,
  1038. modelId: "child-model",
  1039. providerHostname: "child.example.com",
  1040. inputTokens: 150,
  1041. outputTokens: 50,
  1042. totalTokens: 200,
  1043. reasoningTokens: 12,
  1044. cacheReadTokens: 30,
  1045. cacheWriteTokens: 4,
  1046. });
  1047. supervisor.handleFact({
  1048. ...commonFact("subagent-stopped", 8),
  1049. kind: "subagent.lifecycle",
  1050. phase: "stopped",
  1051. agentId: "agent-1",
  1052. agentType: "explore",
  1053. childSessionId: "child-session-1",
  1054. parentToolCallId: "agent-tool-1",
  1055. background: false,
  1056. status: "completed",
  1057. });
  1058. now = 200;
  1059. supervisor.handleFact({
  1060. ...commonFact("agent-tool-complete", 9),
  1061. kind: "tool.lifecycle",
  1062. phase: "completed",
  1063. toolCallId: "agent-tool-1",
  1064. toolName: "Agent",
  1065. });
  1066. now = 210;
  1067. supervisor.handleFact({
  1068. ...commonFact("main-request-2-start", 10),
  1069. kind: "model.request.status",
  1070. requestId: "main-request-2",
  1071. status: "model_request_started",
  1072. providerId: mainId,
  1073. modelId: "main-model",
  1074. providerHostname: "main.example.com",
  1075. transport: "sse",
  1076. querySource: "main_turn",
  1077. attempt: 1,
  1078. maxAttempts: 1,
  1079. });
  1080. supervisor.handleFact({
  1081. ...commonFact("main-generation-2", 11),
  1082. kind: "stream.chunk",
  1083. channel: "text",
  1084. chunkLength: 4,
  1085. firstChunk: true,
  1086. });
  1087. supervisor.handleFact({
  1088. ...commonFact("main-usage-2", 12),
  1089. kind: "usage.delta",
  1090. requestId: "main-request-2",
  1091. providerId: mainId,
  1092. modelId: "main-model",
  1093. providerHostname: "main.example.com",
  1094. inputTokens: 90,
  1095. outputTokens: 30,
  1096. totalTokens: 120,
  1097. reasoningTokens: 0,
  1098. cacheReadTokens: 20,
  1099. cacheWriteTokens: 0,
  1100. });
  1101. now = 240;
  1102. supervisor.handleFact({
  1103. ...commonFact("parent-terminal", 13),
  1104. kind: "turn.terminal",
  1105. status: "success",
  1106. });
  1107. await supervisor.flushReportsForTest();
  1108. const steps = reportsByElement(reportTelemetryEvent, "agent_step");
  1109. expect(steps).toHaveLength(4);
  1110. expect(steps.map((step) => step.eventExtraDetail)).toEqual([
  1111. expect.objectContaining({
  1112. step_type: "reasoning",
  1113. model_name: `${mainReportId}/main-model`,
  1114. total_tokens: "0",
  1115. }),
  1116. expect.objectContaining({
  1117. step_type: "generation",
  1118. model_name: `${mainReportId}/main-model`,
  1119. model_request_id: "main-request-1",
  1120. total_tokens: "100",
  1121. }),
  1122. expect.objectContaining({
  1123. step_type: "tool_call",
  1124. tool_name: "Agent",
  1125. model_name: `${childReportId}/child-model`,
  1126. token_usage_scope: "subagent_requests",
  1127. total_tokens: "200",
  1128. }),
  1129. expect.objectContaining({
  1130. step_type: "generation",
  1131. model_name: `${mainReportId}/main-model`,
  1132. model_request_id: "main-request-2",
  1133. total_tokens: "120",
  1134. }),
  1135. ]);
  1136. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toEqual([
  1137. expect.objectContaining({
  1138. messageId: "command-1",
  1139. eventExtraDetail: expect.objectContaining({
  1140. duration_ms: "140",
  1141. request_time: "100",
  1142. agent_step_cnt: "4",
  1143. }),
  1144. }),
  1145. ]);
  1146. expect(
  1147. reportTelemetryEvent.mock.calls
  1148. .map(([payload]) => payload.elementName)
  1149. .filter(
  1150. (elementName) => elementName === "agent_step" || elementName === "message_completion",
  1151. ),
  1152. ).toEqual(["agent_step", "agent_step", "agent_step", "agent_step", "message_completion"]);
  1153. supervisor.dispose();
  1154. },
  1155. );
  1156. it("父 Agent 与镜像 child tool 共享 agent_id,child tool 使用真实 Subagent 模型", async () => {
  1157. const { platform, reportTelemetryEvent } = createPlatform();
  1158. let now = 100;
  1159. const supervisor = new ConversationTelemetrySupervisor({
  1160. platform,
  1161. workspaceScopeKey: "scope-subagent-tool-agent-id",
  1162. now: () => now,
  1163. });
  1164. supervisor.acceptPromptSeed({
  1165. sessionId: "parent-session",
  1166. sourceCommandId: "parent-command",
  1167. sendTime: now,
  1168. extraDetail: {
  1169. model_name: "main-provider/GLM-5.2-Highspeed",
  1170. model_provider: "main-provider",
  1171. },
  1172. });
  1173. supervisor.handleFact({
  1174. ...commonFact("parent-turn-start", 1, "parent-session"),
  1175. sourceCommandId: "parent-command",
  1176. kind: "turn.started",
  1177. executionKind: "agent",
  1178. });
  1179. supervisor.handleFact({
  1180. ...commonFact("agent-tool-start", 2, "parent-session"),
  1181. sourceCommandId: "parent-command",
  1182. kind: "tool.lifecycle",
  1183. phase: "started",
  1184. toolCallId: "call-parent-agent",
  1185. toolName: "Agent",
  1186. });
  1187. supervisor.handleFact({
  1188. ...commonFact("subagent-spawned", 3, "parent-session"),
  1189. sourceCommandId: "parent-command",
  1190. kind: "subagent.lifecycle",
  1191. phase: "spawned",
  1192. agentId: "agent-child",
  1193. agentType: "Explore",
  1194. childSessionId: "child-session",
  1195. parentToolCallId: "call-parent-agent",
  1196. background: false,
  1197. status: "running",
  1198. });
  1199. supervisor.handleFact({
  1200. ...commonFact("child-request-start", 1, "child-session"),
  1201. sourceCommandId: "child-command",
  1202. turnId: "child-turn",
  1203. kind: "model.request.status",
  1204. requestId: "child-request",
  1205. status: "model_request_started",
  1206. providerId: "qwen-provider",
  1207. modelId: "qwen3.7-max",
  1208. providerHostname: "provider.example.com",
  1209. transport: "sse",
  1210. querySource: "subagent",
  1211. attempt: 1,
  1212. maxAttempts: 1,
  1213. });
  1214. supervisor.handleFact({
  1215. ...commonFact("child-usage", 2, "child-session"),
  1216. sourceCommandId: "child-command",
  1217. turnId: "child-turn",
  1218. kind: "usage.delta",
  1219. requestId: "child-request",
  1220. providerId: "qwen-provider",
  1221. modelId: "qwen3.7-max",
  1222. providerHostname: "provider.example.com",
  1223. inputTokens: 100,
  1224. outputTokens: 20,
  1225. totalTokens: 120,
  1226. reasoningTokens: 0,
  1227. cacheReadTokens: 0,
  1228. cacheWriteTokens: 0,
  1229. });
  1230. const mirroredToolId = "tool_subagent_agent-child_toolu-child";
  1231. const mirroredRelation = {
  1232. agentId: "agent-child",
  1233. agentType: "Explore",
  1234. childSessionId: "child-session",
  1235. childToolCallId: "toolu-child",
  1236. parentToolCallId: "call-parent-agent",
  1237. };
  1238. now = 130;
  1239. supervisor.handleFact({
  1240. ...commonFact("child-tool-start", 4, "parent-session"),
  1241. sourceCommandId: "parent-command",
  1242. kind: "tool.lifecycle",
  1243. phase: "started",
  1244. toolCallId: mirroredToolId,
  1245. toolName: "WebFetch",
  1246. ...mirroredRelation,
  1247. });
  1248. now = 140;
  1249. supervisor.handleFact({
  1250. ...commonFact("subagent-stopped", 5, "parent-session"),
  1251. sourceCommandId: "parent-command",
  1252. kind: "subagent.lifecycle",
  1253. phase: "stopped",
  1254. agentId: "agent-child",
  1255. agentType: "Explore",
  1256. childSessionId: "child-session",
  1257. parentToolCallId: "call-parent-agent",
  1258. background: false,
  1259. status: "completed",
  1260. });
  1261. now = 150;
  1262. supervisor.handleFact({
  1263. // lifecycle 与 mirror 不同流;工具终态即使晚于 stopped 仍需取得 child 归因。
  1264. ...commonFact("child-tool-complete", 6, "parent-session"),
  1265. sourceCommandId: "parent-command",
  1266. kind: "tool.lifecycle",
  1267. phase: "completed",
  1268. toolCallId: mirroredToolId,
  1269. toolName: "WebFetch",
  1270. durationMs: 20,
  1271. ...mirroredRelation,
  1272. });
  1273. now = 170;
  1274. supervisor.handleFact({
  1275. ...commonFact("agent-tool-complete", 7, "parent-session"),
  1276. sourceCommandId: "parent-command",
  1277. kind: "tool.lifecycle",
  1278. phase: "completed",
  1279. toolCallId: "call-parent-agent",
  1280. toolName: "Agent",
  1281. });
  1282. await supervisor.flushReportsForTest();
  1283. const steps = reportsByElement(reportTelemetryEvent, "agent_step");
  1284. const agentStep = steps.find((step) => step.eventExtraDetail.tool_name === "Agent");
  1285. const childToolStep = steps.find((step) => step.eventExtraDetail.tool_name === "WebFetch");
  1286. expect(agentStep?.eventExtraDetail).toEqual(
  1287. expect.objectContaining({
  1288. tool_call_id: "call-parent-agent",
  1289. agent_id: "agent-child",
  1290. agent_role: "foreground subagent",
  1291. model_name: "qwen-provider/qwen3.7-max",
  1292. token_usage_scope: "subagent_requests",
  1293. total_tokens: "120",
  1294. }),
  1295. );
  1296. expect(childToolStep?.eventExtraDetail).toEqual(
  1297. expect.objectContaining({
  1298. tool_call_id: mirroredToolId,
  1299. agent_id: "agent-child",
  1300. agent_role: "foreground subagent",
  1301. model_name: "qwen-provider/qwen3.7-max",
  1302. model_provider: "qwen-provider",
  1303. token_usage_scope: "",
  1304. total_tokens: "0",
  1305. }),
  1306. );
  1307. supervisor.dispose();
  1308. });
  1309. it("父 Agent 非 timeout 终态先到时仍等待 SubagentStopped 回填晚到 usage", async () => {
  1310. const { platform, reportTelemetryEvent } = createPlatform();
  1311. let now = 100;
  1312. const supervisor = new ConversationTelemetrySupervisor({
  1313. platform,
  1314. workspaceScopeKey: "scope-cancelled-foreground-subagent",
  1315. now: () => now,
  1316. });
  1317. startForegroundSubagent(supervisor, now);
  1318. startForegroundSubagentRequest(supervisor);
  1319. now = 200;
  1320. terminateForegroundSubagentParent(supervisor);
  1321. reportForegroundSubagentUsage(supervisor);
  1322. await supervisor.flushReportsForTest();
  1323. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(0);
  1324. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(0);
  1325. now = 250;
  1326. supervisor.handleFact({
  1327. ...commonFact("subagent-stopped", 6, "parent-session"),
  1328. sourceCommandId: "parent-command",
  1329. kind: "subagent.lifecycle",
  1330. phase: "stopped",
  1331. agentId: "agent-1",
  1332. childSessionId: "child-session",
  1333. parentToolCallId: "agent-tool",
  1334. background: false,
  1335. status: "failed",
  1336. });
  1337. await supervisor.flushReportsForTest();
  1338. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toEqual([
  1339. expect.objectContaining({
  1340. messageId: "parent-command",
  1341. eventExtraDetail: expect.objectContaining({
  1342. step_type: "tool_call",
  1343. tool_name: "Agent",
  1344. status: "fail",
  1345. model_name: "qwen-provider/qwen3.7-max",
  1346. model_provider: "qwen-provider",
  1347. provider_name: "provider.example.com",
  1348. model_request_id: "child-request",
  1349. model_request_count: "1",
  1350. token_usage_scope: "subagent_requests",
  1351. input_tokens: "8616",
  1352. output_tokens: "69",
  1353. cache_write_input_tokens: "5797",
  1354. total_tokens: "8685",
  1355. }),
  1356. }),
  1357. ]);
  1358. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toEqual([
  1359. expect.objectContaining({
  1360. messageId: "parent-command",
  1361. eventExtraDetail: expect.objectContaining({
  1362. request_time: "100",
  1363. duration_ms: "100",
  1364. agent_step_cnt: "1",
  1365. }),
  1366. }),
  1367. ]);
  1368. expect(
  1369. reportTelemetryEvent.mock.calls
  1370. .map(([payload]) => payload.elementName)
  1371. .filter(
  1372. (elementName) => elementName === "agent_step" || elementName === "message_completion",
  1373. ),
  1374. ).toEqual(["agent_step", "message_completion"]);
  1375. supervisor.dispose();
  1376. });
  1377. it("main completion 没有 subagent 结果时上报 0,background child 停止本身不计入结果", async () => {
  1378. const { platform, reportTelemetryEvent } = createPlatform();
  1379. const supervisor = new ConversationTelemetrySupervisor({
  1380. platform,
  1381. workspaceScopeKey: "scope-subagent-result-none",
  1382. });
  1383. supervisor.acceptPromptSeed({
  1384. sessionId: "parent-session",
  1385. sourceCommandId: "parent-command",
  1386. sendTime: 100,
  1387. extraDetail: { model_name: "main-model", model_provider: "main-provider" },
  1388. });
  1389. supervisor.handleFact({
  1390. ...commonFact("parent-turn-start", 1, "parent-session"),
  1391. sourceCommandId: "parent-command",
  1392. kind: "turn.started",
  1393. });
  1394. spawnBackgroundSubagent(supervisor, {
  1395. agentId: "background-agent",
  1396. childSessionId: "background-child",
  1397. sourceCommandId: "parent-command",
  1398. parentToolCallId: "background-agent-tool",
  1399. });
  1400. supervisor.handleFact({
  1401. ...commonFact("background-stopped", 2, "parent-session"),
  1402. sourceCommandId: "parent-command",
  1403. kind: "subagent.lifecycle",
  1404. phase: "stopped",
  1405. agentId: "background-agent",
  1406. childSessionId: "background-child",
  1407. parentToolCallId: "background-agent-tool",
  1408. background: true,
  1409. status: "completed",
  1410. });
  1411. supervisor.handleFact({
  1412. ...commonFact("parent-terminal", 3, "parent-session"),
  1413. sourceCommandId: "parent-command",
  1414. kind: "turn.terminal",
  1415. status: "success",
  1416. });
  1417. await supervisor.flushReportsForTest();
  1418. expect(completionAgentCompositions(reportTelemetryEvent)).toEqual(["main_only"]);
  1419. supervisor.dispose();
  1420. });
  1421. it("foreground subagent 结果在 child stopped 后计为 main_plus_fg", async () => {
  1422. const { platform, reportTelemetryEvent } = createPlatform();
  1423. const supervisor = new ConversationTelemetrySupervisor({
  1424. platform,
  1425. workspaceScopeKey: "scope-subagent-result-foreground",
  1426. });
  1427. startForegroundSubagent(supervisor, 100);
  1428. supervisor.handleFact({
  1429. ...commonFact("foreground-stopped", 4, "parent-session"),
  1430. sourceCommandId: "parent-command",
  1431. kind: "subagent.lifecycle",
  1432. phase: "stopped",
  1433. agentId: "agent-1",
  1434. childSessionId: "child-session",
  1435. parentToolCallId: "agent-tool",
  1436. background: false,
  1437. status: "completed",
  1438. });
  1439. supervisor.handleFact({
  1440. ...commonFact("parent-terminal", 5, "parent-session"),
  1441. sourceCommandId: "parent-command",
  1442. kind: "turn.terminal",
  1443. status: "success",
  1444. });
  1445. await supervisor.flushReportsForTest();
  1446. expect(completionAgentCompositions(reportTelemetryEvent)).toEqual(["main_plus_fg"]);
  1447. supervisor.dispose();
  1448. });
  1449. it("background notification dequeue 后启动的 main turn 计为 main_plus_bg", async () => {
  1450. const { platform, reportTelemetryEvent } = createPlatform();
  1451. const supervisor = new ConversationTelemetrySupervisor({
  1452. platform,
  1453. workspaceScopeKey: "scope-subagent-result-background",
  1454. });
  1455. supervisor.handleFact({
  1456. ...commonFact("background-wake-start", 1, "session-1"),
  1457. sourceCommandId: "background-wake-command",
  1458. kind: "turn.started",
  1459. inputSource: "background_task",
  1460. backgroundSource: "subagent",
  1461. });
  1462. supervisor.handleFact({
  1463. ...commonFact("background-wake-terminal", 2, "session-1"),
  1464. sourceCommandId: "background-wake-command",
  1465. kind: "turn.terminal",
  1466. status: "success",
  1467. backgroundSubagentResultConsumed: true,
  1468. });
  1469. await supervisor.flushReportsForTest();
  1470. expect(completionAgentCompositions(reportTelemetryEvent)).toEqual(["main_plus_bg"]);
  1471. expect(
  1472. reportsByElement(reportTelemetryEvent, "message_completion")[0]?.eventExtraDetail,
  1473. ).toMatchObject({
  1474. message_source: "background_subagent",
  1475. });
  1476. supervisor.dispose();
  1477. });
  1478. it("background notification 无具体来源时保留 background_task 来源", async () => {
  1479. const { platform, reportTelemetryEvent } = createPlatform();
  1480. const supervisor = new ConversationTelemetrySupervisor({
  1481. platform,
  1482. workspaceScopeKey: "scope-background-bash-composition",
  1483. });
  1484. supervisor.handleFact({
  1485. ...commonFact("background-bash-start", 1, "session-1"),
  1486. sourceCommandId: "background-bash-command",
  1487. kind: "turn.started",
  1488. inputSource: "background_task",
  1489. });
  1490. supervisor.handleFact({
  1491. ...commonFact("background-bash-terminal", 2, "session-1"),
  1492. sourceCommandId: "background-bash-command",
  1493. kind: "turn.terminal",
  1494. status: "success",
  1495. backgroundSubagentResultConsumed: true,
  1496. });
  1497. await supervisor.flushReportsForTest();
  1498. expect(completionAgentCompositions(reportTelemetryEvent)).toEqual(["main_plus_bg"]);
  1499. expect(
  1500. reportsByElement(reportTelemetryEvent, "message_completion")[0]?.eventExtraDetail,
  1501. ).toMatchObject({ message_source: "background_task" });
  1502. supervisor.dispose();
  1503. });
  1504. it("background Bash 发起后在 active-loop 消费 subagent 结果仍保留 background_task 来源", async () => {
  1505. const { platform, reportTelemetryEvent } = createPlatform();
  1506. const supervisor = new ConversationTelemetrySupervisor({
  1507. platform,
  1508. workspaceScopeKey: "scope-background-bash-active-loop-subagent",
  1509. });
  1510. supervisor.handleFact({
  1511. ...commonFact("background-bash-active-loop-start", 1, "session-1"),
  1512. sourceCommandId: "background-bash-active-loop-command",
  1513. kind: "turn.started",
  1514. inputSource: "background_task",
  1515. backgroundSource: "bash",
  1516. });
  1517. supervisor.handleFact({
  1518. ...commonFact("background-bash-active-loop-terminal", 2, "session-1"),
  1519. sourceCommandId: "background-bash-active-loop-command",
  1520. kind: "turn.terminal",
  1521. status: "success",
  1522. backgroundSubagentResultConsumed: true,
  1523. });
  1524. await supervisor.flushReportsForTest();
  1525. expect(completionAgentCompositions(reportTelemetryEvent)).toEqual(["main_plus_bg"]);
  1526. expect(
  1527. reportsByElement(reportTelemetryEvent, "message_completion")[0]?.eventExtraDetail,
  1528. ).toMatchObject({ message_source: "background_task" });
  1529. supervisor.dispose();
  1530. });
  1531. it("用户 query active-loop 消费 background subagent 结果仍保持 chat 来源", async () => {
  1532. const { platform, reportTelemetryEvent } = createPlatform();
  1533. const supervisor = new ConversationTelemetrySupervisor({
  1534. platform,
  1535. workspaceScopeKey: "scope-user-query-background-result",
  1536. });
  1537. supervisor.acceptPromptSeed({
  1538. sessionId: "session-1",
  1539. sourceCommandId: "user-command",
  1540. sendTime: 1,
  1541. extraDetail: { message_source: "chat" },
  1542. });
  1543. supervisor.handleFact({
  1544. ...commonFact("user-turn-start", 1, "session-1"),
  1545. sourceCommandId: "user-command",
  1546. kind: "turn.started",
  1547. executionKind: "agent",
  1548. });
  1549. supervisor.handleFact({
  1550. ...commonFact("user-turn-terminal", 2, "session-1"),
  1551. sourceCommandId: "user-command",
  1552. kind: "turn.terminal",
  1553. status: "success",
  1554. backgroundSubagentResultConsumed: true,
  1555. });
  1556. await supervisor.flushReportsForTest();
  1557. expect(completionAgentCompositions(reportTelemetryEvent)).toEqual(["main_plus_bg"]);
  1558. expect(
  1559. reportsByElement(reportTelemetryEvent, "message_completion")[0]?.eventExtraDetail,
  1560. ).toMatchObject({
  1561. message_source: "chat",
  1562. });
  1563. supervisor.dispose();
  1564. });
  1565. it("同一 main wake turn 同时消费结果时计为 main_plus_fg_bg", async () => {
  1566. const { platform, reportTelemetryEvent } = createPlatform();
  1567. const supervisor = new ConversationTelemetrySupervisor({
  1568. platform,
  1569. workspaceScopeKey: "scope-subagent-result-mixed",
  1570. });
  1571. supervisor.handleFact({
  1572. ...commonFact("mixed-wake-start", 1, "session-1"),
  1573. sourceCommandId: "mixed-wake-command",
  1574. kind: "turn.started",
  1575. inputSource: "background_task",
  1576. });
  1577. supervisor.handleFact({
  1578. ...commonFact("mixed-agent-start", 2, "session-1"),
  1579. sourceCommandId: "mixed-wake-command",
  1580. kind: "tool.lifecycle",
  1581. phase: "started",
  1582. toolCallId: "mixed-agent-tool",
  1583. toolName: "Agent",
  1584. });
  1585. supervisor.handleFact({
  1586. ...commonFact("mixed-foreground-spawned", 3, "session-1"),
  1587. sourceCommandId: "mixed-wake-command",
  1588. kind: "subagent.lifecycle",
  1589. phase: "spawned",
  1590. agentId: "foreground-agent",
  1591. childSessionId: "mixed-foreground-child",
  1592. parentToolCallId: "mixed-agent-tool",
  1593. background: false,
  1594. status: "running",
  1595. });
  1596. supervisor.handleFact({
  1597. ...commonFact("mixed-foreground-stopped", 4, "session-1"),
  1598. sourceCommandId: "mixed-wake-command",
  1599. kind: "subagent.lifecycle",
  1600. phase: "stopped",
  1601. agentId: "foreground-agent",
  1602. childSessionId: "mixed-foreground-child",
  1603. parentToolCallId: "mixed-agent-tool",
  1604. background: false,
  1605. status: "completed",
  1606. });
  1607. supervisor.handleFact({
  1608. ...commonFact("mixed-agent-completed", 5, "session-1"),
  1609. sourceCommandId: "mixed-wake-command",
  1610. kind: "tool.lifecycle",
  1611. phase: "completed",
  1612. toolCallId: "mixed-agent-tool",
  1613. toolName: "Agent",
  1614. });
  1615. supervisor.handleFact({
  1616. ...commonFact("mixed-wake-terminal", 6, "session-1"),
  1617. sourceCommandId: "mixed-wake-command",
  1618. kind: "turn.terminal",
  1619. status: "success",
  1620. backgroundSubagentResultConsumed: true,
  1621. });
  1622. await supervisor.flushReportsForTest();
  1623. expect(completionAgentCompositions(reportTelemetryEvent)).toEqual(["main_plus_fg_bg"]);
  1624. supervisor.dispose();
  1625. });
  1626. it("background child 工具逐条上报,Agent step 独占累计 token,不生成 thought/generation/completion", async () => {
  1627. const { platform, reportTelemetryEvent } = createPlatform();
  1628. let now = 100;
  1629. const supervisor = new ConversationTelemetrySupervisor({
  1630. platform,
  1631. workspaceScopeKey: "scope-background-tool-step",
  1632. now: () => now,
  1633. });
  1634. supervisor.acceptPromptSeed({
  1635. sessionId: "parent-session",
  1636. sourceCommandId: "parent-command",
  1637. sendTime: now,
  1638. memoryEnabled: true,
  1639. extraDetail: {},
  1640. });
  1641. spawnBackgroundSubagent(supervisor, {
  1642. agentId: "agent-background",
  1643. childSessionId: "child-background",
  1644. });
  1645. now = 120;
  1646. supervisor.handleFact({
  1647. ...commonFact("child-model-started", 1, "child-background"),
  1648. sourceCommandId: undefined,
  1649. kind: "model.request.status",
  1650. requestId: "child-request",
  1651. status: "model_request_started",
  1652. providerId: "child-provider",
  1653. modelId: "child-model",
  1654. providerHostname: "child.example.com",
  1655. transport: "sse",
  1656. querySource: "subagent",
  1657. attempt: 1,
  1658. maxAttempts: 1,
  1659. });
  1660. now = 130;
  1661. supervisor.handleFact({
  1662. ...commonFact("child-thought", 2, "child-background"),
  1663. sourceCommandId: undefined,
  1664. kind: "stream.chunk",
  1665. channel: "thought",
  1666. chunkLength: 10,
  1667. firstChunk: true,
  1668. });
  1669. now = 140;
  1670. supervisor.handleFact({
  1671. ...commonFact("child-text", 3, "child-background"),
  1672. sourceCommandId: undefined,
  1673. kind: "stream.chunk",
  1674. channel: "text",
  1675. chunkLength: 10,
  1676. firstChunk: true,
  1677. assistantMessageId: "child-message",
  1678. });
  1679. now = 150;
  1680. supervisor.handleFact({
  1681. ...commonFact("child-usage", 4, "child-background"),
  1682. sourceCommandId: undefined,
  1683. kind: "usage.delta",
  1684. requestId: "child-request",
  1685. providerId: "child-provider",
  1686. modelId: "child-model",
  1687. inputTokens: 100,
  1688. outputTokens: 20,
  1689. totalTokens: 120,
  1690. reasoningTokens: 3,
  1691. cacheReadTokens: 4,
  1692. cacheWriteTokens: 5,
  1693. });
  1694. now = 160;
  1695. supervisor.handleFact({
  1696. ...commonFact("child-tool-started", 5, "child-background"),
  1697. sourceCommandId: undefined,
  1698. kind: "tool.lifecycle",
  1699. phase: "started",
  1700. toolCallId: "child-tool",
  1701. toolName: "Bash",
  1702. });
  1703. now = 180;
  1704. supervisor.handleFact({
  1705. ...commonFact("child-tool-completed", 6, "child-background"),
  1706. sourceCommandId: undefined,
  1707. kind: "tool.lifecycle",
  1708. phase: "completed",
  1709. toolCallId: "child-tool",
  1710. toolName: "Bash",
  1711. });
  1712. now = 190;
  1713. supervisor.handleFact({
  1714. ...commonFact("child-terminal", 7, "child-background"),
  1715. sourceCommandId: undefined,
  1716. kind: "turn.terminal",
  1717. status: "success",
  1718. });
  1719. await supervisor.flushReportsForTest();
  1720. expect(
  1721. reportTelemetryEvent.mock.calls
  1722. .map(([payload]) => payload.elementName)
  1723. .filter((name) => name === "agent_step" || name === "message_completion"),
  1724. ).toEqual(["agent_step", "agent_step"]);
  1725. expect(
  1726. reportsByElement(reportTelemetryEvent, "agent_step").map(
  1727. (report) => report.eventExtraDetail.memory_enabled,
  1728. ),
  1729. ).toEqual(["1", "1"]);
  1730. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toEqual([
  1731. expect.objectContaining({
  1732. talkId: "parent-session",
  1733. messageId: "parent-command",
  1734. eventExtraDetail: expect.objectContaining({
  1735. step_type: "tool_call",
  1736. tool_name: "Bash",
  1737. tool_call_id: "tool_subagent_agent-background_child-tool",
  1738. loop_index: "1",
  1739. agent_id: "agent-background",
  1740. agent_role: "background subagent",
  1741. model_name: "child-provider/child-model",
  1742. model_provider: "child-provider",
  1743. provider_name: "child.example.com",
  1744. token_usage_scope: "",
  1745. total_tokens: "0",
  1746. duration_ms: "20",
  1747. }),
  1748. }),
  1749. expect.objectContaining({
  1750. talkId: "parent-session",
  1751. messageId: "parent-command",
  1752. eventExtraDetail: expect.objectContaining({
  1753. step_type: "tool_call",
  1754. tool_name: "Agent",
  1755. tool_call_id: "tool_subagent_agent-background_agent-background-parent-tool",
  1756. loop_index: "2",
  1757. agent_id: "agent-background",
  1758. agent_role: "background subagent",
  1759. model_name: "child-provider/child-model",
  1760. token_usage_scope: "subagent_requests",
  1761. model_request_count: "1",
  1762. input_tokens: "100",
  1763. output_tokens: "20",
  1764. total_tokens: "120",
  1765. reasoning_tokens: "3",
  1766. cached_tokens: "4",
  1767. cache_write_input_tokens: "5",
  1768. duration_ms: "90",
  1769. status: "success",
  1770. }),
  1771. }),
  1772. ]);
  1773. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(0);
  1774. supervisor.dispose();
  1775. });
  1776. it.each(["success", "failed", "interrupted"] as const)(
  1777. "background %s 终态保留每个 child 的累计 usage,重复 usage/stopped/terminal 不重复上报",
  1778. async (status) => {
  1779. const { platform, reportTelemetryEvent } = createPlatform();
  1780. const supervisor = new ConversationTelemetrySupervisor({
  1781. platform,
  1782. workspaceScopeKey: "bg-usage",
  1783. });
  1784. startForegroundSubagent(supervisor, 10);
  1785. for (const agentId of ["a", "b", "c"]) {
  1786. spawnBackgroundSubagent(supervisor, { agentId, childSessionId: agentId });
  1787. supervisor.handleFact({
  1788. ...commonFact(`${agentId}-request`, 1, agentId),
  1789. kind: "model.request.status",
  1790. status: "model_request_started",
  1791. requestId: `${agentId}-r1`,
  1792. providerId: "provider",
  1793. modelId: "model",
  1794. transport: "sse",
  1795. querySource: "subagent",
  1796. attempt: 1,
  1797. maxAttempts: 1,
  1798. });
  1799. }
  1800. terminateForegroundSubagentParent(supervisor);
  1801. supervisor.handleFact({
  1802. ...commonFact("fg-stopped", 8, "parent-session"),
  1803. kind: "subagent.lifecycle",
  1804. phase: "stopped",
  1805. agentId: "agent-1",
  1806. childSessionId: "child-session",
  1807. parentToolCallId: "agent-tool",
  1808. background: false,
  1809. status: "stopped",
  1810. });
  1811. await supervisor.flushReportsForTest();
  1812. const parentCompletion = reportsByElement(reportTelemetryEvent, "message_completion");
  1813. expect(parentCompletion).toHaveLength(1);
  1814. for (const [index, agentId] of ["a", "b", "c"].entries()) {
  1815. for (const [eventId, requestId] of [
  1816. ["u1", "r1"],
  1817. ["u1-copy", "r1"],
  1818. ["u2", "r2"],
  1819. ]) {
  1820. supervisor.handleFact({
  1821. ...commonFact(`${agentId}-${eventId}`, 10, agentId),
  1822. kind: "usage.delta",
  1823. requestId: `${agentId}-${requestId}`,
  1824. providerId: "provider",
  1825. modelId: "model",
  1826. inputTokens: 100 * (index + 1),
  1827. outputTokens: 20,
  1828. totalTokens: 100 * (index + 1) + 20,
  1829. reasoningTokens: 0,
  1830. cacheReadTokens: 0,
  1831. cacheWriteTokens: 0,
  1832. });
  1833. }
  1834. await supervisor.flushReportsForTest();
  1835. expect(
  1836. reportsByElement(reportTelemetryEvent, "agent_step").filter(
  1837. (r) => r.eventExtraDetail.agent_id === agentId,
  1838. ),
  1839. ).toHaveLength(0);
  1840. for (const eventId of ["terminal", "terminal-copy"]) {
  1841. supervisor.handleFact({
  1842. ...commonFact(`${agentId}-${eventId}`, 20, agentId),
  1843. kind: "turn.terminal",
  1844. status,
  1845. ...(status !== "success"
  1846. ? { errorCode: "CHILD_FAILED", errorMessage: "child stopped" }
  1847. : {}),
  1848. });
  1849. }
  1850. supervisor.handleFact({
  1851. ...commonFact(`${agentId}-stopped`, 21, "parent-session"),
  1852. kind: "subagent.lifecycle",
  1853. phase: "stopped",
  1854. background: true,
  1855. agentId,
  1856. childSessionId: agentId,
  1857. parentToolCallId: `${agentId}-parent-tool`,
  1858. status: "stopped",
  1859. });
  1860. }
  1861. await supervisor.flushReportsForTest();
  1862. const background = reportsByElement(reportTelemetryEvent, "agent_step").filter(
  1863. (r) => r.eventExtraDetail.agent_role === "background subagent",
  1864. );
  1865. expect(background).toHaveLength(3);
  1866. for (const [index, step] of background.entries()) {
  1867. expect(step.eventExtraDetail).toMatchObject({
  1868. tool_name: "Agent",
  1869. loop_index: "1",
  1870. model_request_count: "2",
  1871. token_usage_scope: "subagent_requests",
  1872. total_tokens: String(240 + index * 200),
  1873. status: status === "success" ? "success" : "fail",
  1874. error_msg: status === "success" ? "" : "[redacted]",
  1875. });
  1876. }
  1877. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toEqual(
  1878. parentCompletion,
  1879. );
  1880. supervisor.dispose();
  1881. },
  1882. );
  1883. it.each([
  1884. { status: "completed", hasUsage: true },
  1885. { status: "failed", hasUsage: true },
  1886. { status: "stopped", hasUsage: true },
  1887. { status: "completed", hasUsage: false },
  1888. { status: "failed", hasUsage: false },
  1889. { status: "stopped", hasUsage: false },
  1890. ])(
  1891. "background 仅 stopped=$status 也结算一次(hasUsage=$hasUsage)",
  1892. async ({ status, hasUsage }) => {
  1893. const { platform, reportTelemetryEvent, reportArmsCustomEvent } = createPlatform();
  1894. let now = 100;
  1895. const supervisor = new ConversationTelemetrySupervisor({
  1896. platform,
  1897. workspaceScopeKey: "bg-stopped-usage",
  1898. now: () => now,
  1899. });
  1900. spawnBackgroundSubagent(supervisor, { agentId: "bg", childSessionId: "child-bg" });
  1901. supervisor.handleFact({
  1902. ...commonFact("request", 1, "child-bg"),
  1903. kind: "model.request.status",
  1904. status: "model_request_started",
  1905. requestId: "request-bg",
  1906. providerId: "provider",
  1907. modelId: "model",
  1908. providerHostname: "provider.example.com",
  1909. transport: "sse",
  1910. querySource: "subagent",
  1911. attempt: 1,
  1912. maxAttempts: 1,
  1913. });
  1914. if (hasUsage) {
  1915. supervisor.handleFact({
  1916. ...commonFact("usage", 2, "child-bg"),
  1917. kind: "usage.delta",
  1918. requestId: "request-bg",
  1919. inputTokens: 100,
  1920. outputTokens: 20,
  1921. totalTokens: 120,
  1922. reasoningTokens: 5,
  1923. cacheReadTokens: 30,
  1924. cacheWriteTokens: 40,
  1925. });
  1926. }
  1927. await supervisor.flushReportsForTest();
  1928. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(0);
  1929. now = 250;
  1930. const armsBeforeStopped = reportArmsCustomEvent.mock.calls.slice();
  1931. const stopped = {
  1932. ...commonFact("stopped", 3, "parent-session"),
  1933. kind: "subagent.lifecycle" as const,
  1934. phase: "stopped" as const,
  1935. background: true,
  1936. agentId: "bg",
  1937. childSessionId: "child-bg",
  1938. parentToolCallId: "bg-parent-tool",
  1939. status,
  1940. ...(status === "completed"
  1941. ? {}
  1942. : { errorMessage: "provider failure or user cancellation" }),
  1943. };
  1944. supervisor.handleFact(stopped);
  1945. await supervisor.flushReportsForTest();
  1946. const reports = reportsByElement(reportTelemetryEvent, "agent_step");
  1947. expect(reports).toEqual([
  1948. expect.objectContaining({
  1949. talkId: "parent-session",
  1950. messageId: "parent-command",
  1951. eventExtraDetail: expect.objectContaining({
  1952. agent_id: "bg",
  1953. agent_role: "background subagent",
  1954. tool_name: "Agent",
  1955. tool_call_id: "tool_subagent_bg_bg-parent-tool",
  1956. child_session_id: "child-bg",
  1957. parent_tool_call_id: "bg-parent-tool",
  1958. loop_index: "1",
  1959. duration_ms: "150",
  1960. model_name: "provider/model",
  1961. model_provider: "provider",
  1962. provider_name: "provider.example.com",
  1963. model_request_count: hasUsage ? "1" : "0",
  1964. token_usage_scope: hasUsage ? "subagent_requests" : "",
  1965. input_tokens: hasUsage ? "100" : "0",
  1966. output_tokens: hasUsage ? "20" : "0",
  1967. total_tokens: hasUsage ? "120" : "0",
  1968. reasoning_tokens: hasUsage ? "5" : "0",
  1969. cached_tokens: hasUsage ? "30" : "0",
  1970. cache_write_input_tokens: hasUsage ? "40" : "0",
  1971. status: status === "completed" ? "success" : "fail",
  1972. error_type: status === "completed" ? "" : "TOOL_EXEC_ERROR",
  1973. error_msg: status === "completed" ? "" : "[redacted]",
  1974. }),
  1975. }),
  1976. ]);
  1977. supervisor.handleFact({ ...stopped, eventId: "stopped-copy" });
  1978. supervisor.handleFact({
  1979. ...commonFact("late-terminal", 4, "child-bg"),
  1980. kind: "turn.terminal",
  1981. status: "failed",
  1982. errorMessage: "late error must not replace the first terminal",
  1983. });
  1984. await supervisor.flushReportsForTest();
  1985. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toEqual(reports);
  1986. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(0);
  1987. expect(reportsByElement(reportTelemetryEvent, "send_btn")).toHaveLength(0);
  1988. expect(reportArmsCustomEvent.mock.calls).toEqual(armsBeforeStopped);
  1989. supervisor.dispose();
  1990. },
  1991. );
  1992. it("background child 的 loop_index 按 child 独立递增,并行 child 互不影响", async () => {
  1993. const { platform, reportTelemetryEvent } = createPlatform();
  1994. const supervisor = new ConversationTelemetrySupervisor({
  1995. platform,
  1996. workspaceScopeKey: "scope-background-loop-index",
  1997. now: () => 100,
  1998. });
  1999. spawnBackgroundSubagent(supervisor, {
  2000. agentId: "agent-a",
  2001. childSessionId: "child-a",
  2002. });
  2003. spawnBackgroundSubagent(supervisor, {
  2004. agentId: "agent-b",
  2005. childSessionId: "child-b",
  2006. });
  2007. for (const [index, childSessionId, , toolCallId] of [
  2008. ["a-1", "child-a", "agent-a", "tool-a-1"],
  2009. ["b-1", "child-b", "agent-b", "tool-b-1"],
  2010. ["a-2", "child-a", "agent-a", "tool-a-2"],
  2011. ["b-2", "child-b", "agent-b", "tool-b-2"],
  2012. ] as const) {
  2013. supervisor.handleFact({
  2014. ...commonFact(`${index}-started`, 10, childSessionId),
  2015. sourceCommandId: undefined,
  2016. kind: "tool.lifecycle",
  2017. phase: "started",
  2018. toolCallId,
  2019. toolName: "Read",
  2020. });
  2021. supervisor.handleFact({
  2022. ...commonFact(`${index}-completed`, 11, childSessionId),
  2023. sourceCommandId: undefined,
  2024. kind: "tool.lifecycle",
  2025. phase: "completed",
  2026. toolCallId,
  2027. toolName: "Read",
  2028. });
  2029. }
  2030. await supervisor.flushReportsForTest();
  2031. const steps = reportsByElement(reportTelemetryEvent, "agent_step");
  2032. expect(
  2033. steps.map((step) => [
  2034. step.eventExtraDetail.agent_id,
  2035. step.eventExtraDetail.loop_index,
  2036. step.eventExtraDetail.tool_call_id,
  2037. ]),
  2038. ).toEqual([
  2039. ["agent-a", "1", "tool_subagent_agent-a_tool-a-1"],
  2040. ["agent-b", "1", "tool_subagent_agent-b_tool-b-1"],
  2041. ["agent-a", "2", "tool_subagent_agent-a_tool-a-2"],
  2042. ["agent-b", "2", "tool_subagent_agent-b_tool-b-2"],
  2043. ]);
  2044. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(0);
  2045. supervisor.dispose();
  2046. });
  2047. it("background stopped 汇总后仍收口全部已开始工具,不重复汇总或补算晚到 usage", async () => {
  2048. const { platform, reportTelemetryEvent } = createPlatform();
  2049. let now = 100;
  2050. const supervisor = new ConversationTelemetrySupervisor({
  2051. platform,
  2052. workspaceScopeKey: "scope-background-late-tool-terminal",
  2053. now: () => now,
  2054. });
  2055. spawnBackgroundSubagent(supervisor, {
  2056. agentId: "agent-background",
  2057. childSessionId: "child-background",
  2058. });
  2059. supervisor.handleFact({
  2060. ...commonFact("child-tool-started", 2, "child-background"),
  2061. sourceCommandId: undefined,
  2062. kind: "tool.lifecycle",
  2063. phase: "started",
  2064. toolCallId: "child-tool",
  2065. toolName: "Bash",
  2066. });
  2067. supervisor.handleFact({
  2068. ...commonFact("child-tool-2-started", 3, "child-background"),
  2069. kind: "tool.lifecycle",
  2070. phase: "started",
  2071. toolCallId: "child-tool-2",
  2072. toolName: "Read",
  2073. });
  2074. const usage = {
  2075. ...commonFact("child-usage", 4, "child-background"),
  2076. kind: "usage.delta" as const,
  2077. requestId: "child-request",
  2078. inputTokens: 100,
  2079. outputTokens: 20,
  2080. totalTokens: 120,
  2081. reasoningTokens: 0,
  2082. cacheReadTokens: 0,
  2083. cacheWriteTokens: 0,
  2084. };
  2085. supervisor.handleFact(usage);
  2086. now = 110;
  2087. const permission = {
  2088. ...commonFact("permission-requested", 5, "child-background"),
  2089. kind: "permission.lifecycle" as const,
  2090. phase: "requested" as const,
  2091. requestId: "child-permission",
  2092. toolCallId: "child-tool",
  2093. };
  2094. supervisor.handleFact(permission);
  2095. now = 120;
  2096. supervisor.handleFact({
  2097. ...commonFact("subagent-stopped", 3, "parent-session"),
  2098. sourceCommandId: "parent-command",
  2099. kind: "subagent.lifecycle",
  2100. phase: "stopped",
  2101. agentId: "agent-background",
  2102. childSessionId: "child-background",
  2103. parentToolCallId: "agent-background-parent-tool",
  2104. background: true,
  2105. status: "stopped",
  2106. });
  2107. now = 150;
  2108. supervisor.handleFact({ ...permission, eventId: "permission-resolved", phase: "resolved" });
  2109. // stopped 后不能因未知工具/权限事实重新开启一份 telemetry 工作。
  2110. supervisor.handleFact({ ...permission, eventId: "late-permission", toolCallId: "late-tool" });
  2111. supervisor.handleFact({
  2112. ...commonFact("late-tool-started", 6, "child-background"),
  2113. kind: "tool.lifecycle",
  2114. phase: "started",
  2115. toolCallId: "late-tool",
  2116. toolName: "Bash",
  2117. });
  2118. now = 160;
  2119. await supervisor.flushReportsForTest();
  2120. const aggregate = reportsByElement(reportTelemetryEvent, "agent_step");
  2121. expect(aggregate).toHaveLength(1);
  2122. expect(aggregate[0]?.eventExtraDetail).toMatchObject({
  2123. tool_name: "Agent",
  2124. loop_index: "3",
  2125. status: "fail",
  2126. total_tokens: "120",
  2127. token_usage_scope: "subagent_requests",
  2128. });
  2129. supervisor.handleFact({ ...usage, eventId: "late-usage", requestId: "late-request" });
  2130. supervisor.handleFact({
  2131. ...commonFact("stopped-copy", 4, "parent-session"),
  2132. kind: "subagent.lifecycle",
  2133. phase: "stopped",
  2134. agentId: "agent-background",
  2135. childSessionId: "child-background",
  2136. parentToolCallId: "agent-background-parent-tool",
  2137. background: true,
  2138. status: "stopped",
  2139. });
  2140. supervisor.handleFact({
  2141. ...commonFact("child-tool-completed", 4, "child-background"),
  2142. sourceCommandId: undefined,
  2143. kind: "tool.lifecycle",
  2144. phase: "completed",
  2145. toolCallId: "child-tool",
  2146. toolName: "Bash",
  2147. });
  2148. supervisor.handleFact({
  2149. ...commonFact("child-tool-completed-copy", 7, "child-background"),
  2150. kind: "tool.lifecycle",
  2151. phase: "completed",
  2152. toolCallId: "child-tool",
  2153. toolName: "Bash",
  2154. });
  2155. supervisor.handleFact({
  2156. ...commonFact("child-tool-2-completed", 5, "child-background"),
  2157. kind: "tool.lifecycle",
  2158. phase: "completed",
  2159. toolCallId: "child-tool-2",
  2160. toolName: "Read",
  2161. });
  2162. supervisor.handleFact({
  2163. ...commonFact("child-terminal", 5, "child-background"),
  2164. sourceCommandId: undefined,
  2165. kind: "turn.terminal",
  2166. status: "interrupted",
  2167. resultType: "cancelled",
  2168. });
  2169. await supervisor.flushReportsForTest();
  2170. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toEqual([
  2171. ...aggregate,
  2172. expect.objectContaining({
  2173. messageId: "parent-command",
  2174. eventExtraDetail: expect.objectContaining({
  2175. tool_name: "Bash",
  2176. tool_call_id: "tool_subagent_agent-background_child-tool",
  2177. agent_id: "agent-background",
  2178. agent_role: "background subagent",
  2179. total_tokens: "0",
  2180. loop_index: "1",
  2181. waiting_ms: "40",
  2182. }),
  2183. }),
  2184. expect.objectContaining({
  2185. eventExtraDetail: expect.objectContaining({
  2186. tool_name: "Read",
  2187. loop_index: "2",
  2188. total_tokens: "0",
  2189. }),
  2190. }),
  2191. ]);
  2192. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(0);
  2193. supervisor.dispose();
  2194. });
  2195. it("background child 没有待收口工具时在 SubagentStopped 后清理 ledger", async () => {
  2196. const { platform, reportTelemetryEvent } = createPlatform();
  2197. const supervisor = new ConversationTelemetrySupervisor({
  2198. platform,
  2199. workspaceScopeKey: "scope-background-stopped-without-tool",
  2200. now: () => 100,
  2201. });
  2202. spawnBackgroundSubagent(supervisor, {
  2203. agentId: "agent-background",
  2204. childSessionId: "child-background",
  2205. });
  2206. supervisor.handleFact({
  2207. ...commonFact("subagent-stopped", 2, "parent-session"),
  2208. sourceCommandId: "parent-command",
  2209. kind: "subagent.lifecycle",
  2210. phase: "stopped",
  2211. agentId: "agent-background",
  2212. childSessionId: "child-background",
  2213. parentToolCallId: "agent-background-parent-tool",
  2214. background: true,
  2215. status: "failed",
  2216. });
  2217. supervisor.handleFact({
  2218. ...commonFact("late-tool-completed", 3, "child-background"),
  2219. sourceCommandId: undefined,
  2220. kind: "tool.lifecycle",
  2221. phase: "completed",
  2222. toolCallId: "late-tool",
  2223. toolName: "Bash",
  2224. });
  2225. await supervisor.flushReportsForTest();
  2226. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toEqual([
  2227. expect.objectContaining({
  2228. eventExtraDetail: expect.objectContaining({
  2229. tool_name: "Agent",
  2230. status: "fail",
  2231. total_tokens: "0",
  2232. }),
  2233. }),
  2234. ]);
  2235. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(0);
  2236. supervisor.dispose();
  2237. });
  2238. it.each([
  2239. { status: "success", hasUsage: false },
  2240. { status: "failed", hasUsage: false },
  2241. { status: "interrupted", hasUsage: false },
  2242. { status: "success", hasUsage: true },
  2243. ] as const)(
  2244. "background $status 终态无 usage 也上报 Agent step(hasUsage=$hasUsage)",
  2245. async ({ status, hasUsage }) => {
  2246. const { platform, reportTelemetryEvent } = createPlatform();
  2247. const supervisor = new ConversationTelemetrySupervisor({
  2248. platform,
  2249. workspaceScopeKey: "scope-background-terminal-only",
  2250. now: () => 100,
  2251. });
  2252. spawnBackgroundSubagent(supervisor, {
  2253. agentId: "agent-1",
  2254. childSessionId: "child-session",
  2255. });
  2256. startForegroundSubagentRequest(supervisor);
  2257. if (hasUsage) {
  2258. supervisor.handleFact({
  2259. ...commonFact("child-zero-usage", 2, "child-session"),
  2260. kind: "usage.delta",
  2261. requestId: "child-request",
  2262. inputTokens: 0,
  2263. outputTokens: 0,
  2264. totalTokens: 0,
  2265. reasoningTokens: 0,
  2266. cacheReadTokens: 0,
  2267. cacheWriteTokens: 0,
  2268. });
  2269. }
  2270. supervisor.handleFact({
  2271. ...commonFact("child-thought", 3, "child-session"),
  2272. sourceCommandId: undefined,
  2273. kind: "stream.chunk",
  2274. channel: "text",
  2275. chunkLength: 1,
  2276. firstChunk: true,
  2277. });
  2278. await supervisor.flushReportsForTest();
  2279. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(0);
  2280. for (const eventId of ["child-terminal", "duplicate-terminal"]) {
  2281. supervisor.handleFact({
  2282. ...commonFact(eventId, 4, "child-session"),
  2283. sourceCommandId: undefined,
  2284. kind: "turn.terminal",
  2285. status,
  2286. ...(status !== "success" ? { errorMessage: "child stopped without usage" } : {}),
  2287. });
  2288. }
  2289. await supervisor.flushReportsForTest();
  2290. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toEqual([
  2291. expect.objectContaining({
  2292. talkId: "parent-session",
  2293. messageId: "parent-command",
  2294. eventExtraDetail: expect.objectContaining({
  2295. step_type: "tool_call",
  2296. tool_name: "Agent",
  2297. tool_call_id: "tool_subagent_agent-1_agent-1-parent-tool",
  2298. agent_id: "agent-1",
  2299. agent_role: "background subagent",
  2300. loop_index: "1",
  2301. model_name: "qwen-provider/qwen3.7-max",
  2302. model_provider: "qwen-provider",
  2303. provider_name: "provider.example.com",
  2304. model_request_id: hasUsage ? "child-request" : "",
  2305. model_request_count: hasUsage ? "1" : "0",
  2306. token_usage_scope: hasUsage ? "subagent_requests" : "",
  2307. input_tokens: "0",
  2308. output_tokens: "0",
  2309. reasoning_tokens: "0",
  2310. cached_tokens: "0",
  2311. cache_write_input_tokens: "0",
  2312. total_tokens: "0",
  2313. status: status === "success" ? "success" : "fail",
  2314. error_type: status === "success" ? "" : "TOOL_EXEC_ERROR",
  2315. error_msg: status === "success" ? "" : "[redacted]",
  2316. }),
  2317. }),
  2318. ]);
  2319. expect(reportsByElement(reportTelemetryEvent, "send_btn")).toHaveLength(0);
  2320. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(0);
  2321. supervisor.dispose();
  2322. },
  2323. );
  2324. it("background child 的 failed tool lifecycle 按 foreground 口径保留错误", async () => {
  2325. const { platform, reportTelemetryEvent } = createPlatform();
  2326. const supervisor = new ConversationTelemetrySupervisor({
  2327. platform,
  2328. workspaceScopeKey: "scope-background-tool-failed",
  2329. now: () => 100,
  2330. });
  2331. spawnBackgroundSubagent(supervisor, {
  2332. agentId: "agent-background",
  2333. childSessionId: "child-background",
  2334. });
  2335. supervisor.handleFact({
  2336. ...commonFact("child-tool-failed", 1, "child-background"),
  2337. sourceCommandId: undefined,
  2338. kind: "tool.lifecycle",
  2339. phase: "failed",
  2340. toolCallId: "child-tool",
  2341. toolName: "Bash",
  2342. errorCode: "tool_timeout",
  2343. errorMessage: "command timed out",
  2344. });
  2345. await supervisor.flushReportsForTest();
  2346. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toEqual([
  2347. expect.objectContaining({
  2348. eventExtraDetail: expect.objectContaining({
  2349. step_type: "tool_call",
  2350. tool_call_id: "tool_subagent_agent-background_child-tool",
  2351. agent_id: "agent-background",
  2352. agent_role: "background subagent",
  2353. status: "fail",
  2354. error_type: "TOOL_EXEC_ERROR",
  2355. error_msg: "[redacted]",
  2356. }),
  2357. }),
  2358. ]);
  2359. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(0);
  2360. supervisor.dispose();
  2361. });
  2362. it("main completion 后 background child 仍可上报 tool step,但不修改 main completion", async () => {
  2363. const { platform, reportTelemetryEvent } = createPlatform();
  2364. let now = 10;
  2365. const supervisor = new ConversationTelemetrySupervisor({
  2366. platform,
  2367. workspaceScopeKey: "scope-background-after-main",
  2368. now: () => now,
  2369. });
  2370. supervisor.acceptPromptSeed({
  2371. sessionId: "parent-session",
  2372. sourceCommandId: "parent-command",
  2373. sendTime: now,
  2374. extraDetail: { model_name: "main-provider/main-model", model_provider: "main-provider" },
  2375. });
  2376. supervisor.handleFact({
  2377. ...commonFact("parent-started", 1, "parent-session"),
  2378. sourceCommandId: "parent-command",
  2379. kind: "turn.started",
  2380. executionKind: "agent",
  2381. });
  2382. spawnBackgroundSubagent(supervisor, {
  2383. agentId: "agent-background",
  2384. childSessionId: "child-background",
  2385. });
  2386. now = 20;
  2387. supervisor.handleFact({
  2388. ...commonFact("parent-terminal", 2, "parent-session"),
  2389. sourceCommandId: "parent-command",
  2390. kind: "turn.terminal",
  2391. status: "success",
  2392. });
  2393. now = 30;
  2394. supervisor.handleFact({
  2395. ...commonFact("child-tool-started", 1, "child-background"),
  2396. sourceCommandId: undefined,
  2397. kind: "tool.lifecycle",
  2398. phase: "started",
  2399. toolCallId: "child-tool",
  2400. toolName: "Read",
  2401. });
  2402. now = 40;
  2403. supervisor.handleFact({
  2404. ...commonFact("child-tool-completed", 2, "child-background"),
  2405. sourceCommandId: undefined,
  2406. kind: "tool.lifecycle",
  2407. phase: "completed",
  2408. toolCallId: "child-tool",
  2409. toolName: "Read",
  2410. });
  2411. await supervisor.flushReportsForTest();
  2412. expect(
  2413. reportTelemetryEvent.mock.calls
  2414. .map(([payload]) => payload.elementName)
  2415. .filter((name) => name === "agent_step" || name === "message_completion"),
  2416. ).toEqual(["message_completion", "agent_step"]);
  2417. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toEqual([
  2418. expect.objectContaining({
  2419. messageId: "parent-command",
  2420. eventExtraDetail: expect.objectContaining({ agent_step_cnt: "0" }),
  2421. }),
  2422. ]);
  2423. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(1);
  2424. supervisor.dispose();
  2425. });
  2426. it("background mirror 与无 usage 的 child 汇总均不污染 main completion", async () => {
  2427. const { platform, reportTelemetryEvent } = createPlatform();
  2428. const supervisor = new ConversationTelemetrySupervisor({
  2429. platform,
  2430. workspaceScopeKey: "scope-background-mirror-filter",
  2431. now: () => 100,
  2432. });
  2433. supervisor.acceptPromptSeed({
  2434. sessionId: "parent-session",
  2435. sourceCommandId: "parent-command",
  2436. sendTime: 100,
  2437. extraDetail: { model_name: "main-model", model_provider: "main-provider" },
  2438. });
  2439. supervisor.handleFact({
  2440. ...commonFact("parent-started", 1, "parent-session"),
  2441. sourceCommandId: "parent-command",
  2442. kind: "turn.started",
  2443. executionKind: "agent",
  2444. });
  2445. spawnBackgroundSubagent(supervisor, {
  2446. agentId: "agent-background",
  2447. childSessionId: "child-background",
  2448. });
  2449. supervisor.handleFact({
  2450. ...commonFact("mirror-permission-requested", 2, "parent-session"),
  2451. sourceCommandId: "parent-command",
  2452. kind: "permission.lifecycle",
  2453. phase: "requested",
  2454. requestId: "permission-1",
  2455. toolCallId: "tool_subagent_agent-background_child-tool",
  2456. background: true,
  2457. childSessionId: "child-background",
  2458. });
  2459. supervisor.handleFact({
  2460. ...commonFact("mirror-tool-started", 3, "parent-session"),
  2461. sourceCommandId: "parent-command",
  2462. kind: "tool.lifecycle",
  2463. phase: "started",
  2464. toolCallId: "tool_subagent_agent-background_child-tool",
  2465. toolName: "Bash",
  2466. agentId: "agent-background",
  2467. childSessionId: "child-background",
  2468. childToolCallId: "child-tool",
  2469. parentToolCallId: "background-agent-tool",
  2470. background: true,
  2471. });
  2472. supervisor.handleFact({
  2473. ...commonFact("child-tool-started", 1, "child-background"),
  2474. sourceCommandId: undefined,
  2475. kind: "tool.lifecycle",
  2476. phase: "started",
  2477. toolCallId: "child-tool",
  2478. toolName: "Bash",
  2479. });
  2480. supervisor.handleFact({
  2481. ...commonFact("child-permission-requested", 2, "child-background"),
  2482. sourceCommandId: undefined,
  2483. kind: "permission.lifecycle",
  2484. phase: "requested",
  2485. requestId: "permission-1",
  2486. toolCallId: "child-tool",
  2487. });
  2488. supervisor.handleFact({
  2489. ...commonFact("child-permission-resolved", 3, "child-background"),
  2490. sourceCommandId: undefined,
  2491. kind: "permission.lifecycle",
  2492. phase: "resolved",
  2493. requestId: "permission-1",
  2494. toolCallId: "child-tool",
  2495. decision: "allow",
  2496. });
  2497. supervisor.handleFact({
  2498. ...commonFact("child-tool-completed", 4, "child-background"),
  2499. sourceCommandId: undefined,
  2500. kind: "tool.lifecycle",
  2501. phase: "completed",
  2502. toolCallId: "child-tool",
  2503. toolName: "Bash",
  2504. });
  2505. supervisor.handleFact({
  2506. ...commonFact("parent-terminal", 5, "parent-session"),
  2507. sourceCommandId: "parent-command",
  2508. kind: "turn.terminal",
  2509. status: "success",
  2510. });
  2511. supervisor.handleFact({
  2512. ...commonFact("child-terminal", 6, "child-background"),
  2513. sourceCommandId: undefined,
  2514. kind: "turn.terminal",
  2515. status: "success",
  2516. });
  2517. await supervisor.flushReportsForTest();
  2518. expect(
  2519. reportsByElement(reportTelemetryEvent, "agent_step").map((step) => [
  2520. step.eventExtraDetail.tool_name,
  2521. step.eventExtraDetail.loop_index,
  2522. step.eventExtraDetail.total_tokens,
  2523. ]),
  2524. ).toEqual([
  2525. ["Bash", "1", "0"],
  2526. ["Agent", "2", "0"],
  2527. ]);
  2528. expect(
  2529. reportTelemetryEvent.mock.calls
  2530. .map(([payload]) => payload.elementName)
  2531. .filter((name) => name === "agent_step" || name === "message_completion"),
  2532. ).toEqual(["agent_step", "message_completion", "agent_step"]);
  2533. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toEqual([
  2534. expect.objectContaining({
  2535. eventExtraDetail: expect.objectContaining({
  2536. agent_step_cnt: "0",
  2537. waiting_ms: "0",
  2538. }),
  2539. }),
  2540. ]);
  2541. supervisor.dispose();
  2542. });
  2543. it("队列立即发送不会在前一 Subagent terminal deferred 时串用 message 状态", async () => {
  2544. const { platform, reportTelemetryEvent } = createPlatform();
  2545. let now = 100;
  2546. const supervisor = new ConversationTelemetrySupervisor({
  2547. platform,
  2548. workspaceScopeKey: "scope-send-queued-now-after-subagent",
  2549. now: () => now,
  2550. });
  2551. startForegroundSubagent(supervisor, now);
  2552. startForegroundSubagentRequest(supervisor);
  2553. reportForegroundSubagentUsage(supervisor);
  2554. now = 180;
  2555. supervisor.acceptPromptSeed({
  2556. sessionId: "parent-session",
  2557. sourceCommandId: "queued-command",
  2558. sendTime: now,
  2559. extraDetail: {
  2560. model_name: "main-provider/main-model",
  2561. model_provider: "main-provider",
  2562. },
  2563. });
  2564. now = 200;
  2565. terminateForegroundSubagentParent(supervisor);
  2566. const queuedFact = (eventId: string, eventSeq: number) => ({
  2567. ...commonFact(eventId, eventSeq, "parent-session"),
  2568. sourceCommandId: "queued-command",
  2569. turnId: "queued-turn",
  2570. });
  2571. now = 210;
  2572. supervisor.handleFact({
  2573. ...queuedFact("queued-turn-start", 7),
  2574. kind: "turn.started",
  2575. executionKind: "agent",
  2576. });
  2577. now = 220;
  2578. supervisor.handleFact({
  2579. ...queuedFact("queued-request-start", 8),
  2580. kind: "model.request.status",
  2581. requestId: "queued-request",
  2582. status: "model_request_started",
  2583. providerId: "main-provider",
  2584. modelId: "main-model",
  2585. providerHostname: "main.example.com",
  2586. transport: "sse",
  2587. querySource: "main_turn",
  2588. attempt: 1,
  2589. maxAttempts: 1,
  2590. });
  2591. now = 230;
  2592. supervisor.handleFact({
  2593. ...queuedFact("queued-text", 9),
  2594. kind: "stream.chunk",
  2595. channel: "text",
  2596. chunkLength: 5,
  2597. firstChunk: true,
  2598. });
  2599. now = 240;
  2600. supervisor.handleFact({
  2601. ...queuedFact("queued-usage", 10),
  2602. kind: "usage.delta",
  2603. requestId: "queued-request",
  2604. providerId: "main-provider",
  2605. modelId: "main-model",
  2606. providerHostname: "main.example.com",
  2607. inputTokens: 10,
  2608. outputTokens: 2,
  2609. totalTokens: 12,
  2610. reasoningTokens: 0,
  2611. cacheReadTokens: 0,
  2612. cacheWriteTokens: 0,
  2613. });
  2614. now = 250;
  2615. supervisor.handleFact({
  2616. ...queuedFact("queued-turn-terminal", 11),
  2617. kind: "turn.terminal",
  2618. status: "success",
  2619. resultType: "complete",
  2620. });
  2621. await supervisor.flushReportsForTest();
  2622. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(0);
  2623. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(0);
  2624. now = 300;
  2625. supervisor.handleFact({
  2626. ...commonFact("subagent-stopped-before-queued-replay", 12, "parent-session"),
  2627. sourceCommandId: "parent-command",
  2628. kind: "subagent.lifecycle",
  2629. phase: "stopped",
  2630. agentId: "agent-1",
  2631. childSessionId: "child-session",
  2632. parentToolCallId: "agent-tool",
  2633. background: false,
  2634. status: "failed",
  2635. });
  2636. await supervisor.flushReportsForTest();
  2637. expect(
  2638. reportsByElement(reportTelemetryEvent, "send_btn").map((payload) => payload.messageId),
  2639. ).toEqual(["parent-command", "queued-command"]);
  2640. expect(
  2641. reportsByElement(reportTelemetryEvent, "agent_step").map((payload) => ({
  2642. messageId: payload.messageId,
  2643. stepType: payload.eventExtraDetail.step_type,
  2644. tokenScope: payload.eventExtraDetail.token_usage_scope,
  2645. totalTokens: payload.eventExtraDetail.total_tokens,
  2646. })),
  2647. ).toEqual([
  2648. {
  2649. messageId: "parent-command",
  2650. stepType: "tool_call",
  2651. tokenScope: "subagent_requests",
  2652. totalTokens: "8685",
  2653. },
  2654. {
  2655. messageId: "queued-command",
  2656. stepType: "generation",
  2657. tokenScope: "model_request",
  2658. totalTokens: "12",
  2659. },
  2660. ]);
  2661. expect(
  2662. reportsByElement(reportTelemetryEvent, "message_completion").map((payload) => ({
  2663. messageId: payload.messageId,
  2664. requestTime: payload.eventExtraDetail.request_time,
  2665. duration: payload.eventExtraDetail.duration_ms,
  2666. stepCount: payload.eventExtraDetail.agent_step_cnt,
  2667. })),
  2668. ).toEqual([
  2669. {
  2670. messageId: "parent-command",
  2671. requestTime: "100",
  2672. duration: "100",
  2673. stepCount: "1",
  2674. },
  2675. {
  2676. messageId: "queued-command",
  2677. requestTime: "180",
  2678. duration: "70",
  2679. stepCount: "1",
  2680. },
  2681. ]);
  2682. expect(
  2683. reportTelemetryEvent.mock.calls
  2684. .map(([payload]) => payload.elementName)
  2685. .filter(
  2686. (elementName) => elementName === "agent_step" || elementName === "message_completion",
  2687. ),
  2688. ).toEqual(["agent_step", "message_completion", "agent_step", "message_completion"]);
  2689. supervisor.dispose();
  2690. });
  2691. it("Agent timeout 先于 SubagentStopped 时立即按已知 usage 收口且迟到 stopped 不重复", async () => {
  2692. const { platform, reportTelemetryEvent } = createPlatform();
  2693. let now = 100;
  2694. const supervisor = new ConversationTelemetrySupervisor({
  2695. platform,
  2696. workspaceScopeKey: "scope-timeout-first-foreground-subagent",
  2697. now: () => now,
  2698. });
  2699. startForegroundSubagent(supervisor, now);
  2700. startForegroundSubagentRequest(supervisor);
  2701. reportForegroundSubagentUsage(supervisor);
  2702. now = 200;
  2703. supervisor.handleFact({
  2704. ...commonFact("parent-turn-terminal", 4, "parent-session"),
  2705. sourceCommandId: "parent-command",
  2706. kind: "turn.terminal",
  2707. status: "interrupted",
  2708. resultType: "cancelled",
  2709. });
  2710. await supervisor.flushReportsForTest();
  2711. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(0);
  2712. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(0);
  2713. now = 210;
  2714. supervisor.handleFact({
  2715. ...commonFact("agent-tool-timeout", 5, "parent-session"),
  2716. sourceCommandId: "parent-command",
  2717. kind: "tool.lifecycle",
  2718. phase: "failed",
  2719. toolCallId: "agent-tool",
  2720. toolName: "Agent",
  2721. errorCode: "tool_timeout",
  2722. errorMessage: "Tool execution timed out after 600000ms",
  2723. });
  2724. await supervisor.flushReportsForTest();
  2725. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toEqual([
  2726. expect.objectContaining({
  2727. messageId: "parent-command",
  2728. eventExtraDetail: expect.objectContaining({
  2729. step_type: "tool_call",
  2730. tool_name: "Agent",
  2731. duration_ms: "110",
  2732. status: "fail",
  2733. model_name: "qwen-provider/qwen3.7-max",
  2734. model_provider: "qwen-provider",
  2735. provider_name: "provider.example.com",
  2736. model_request_id: "child-request",
  2737. model_request_count: "1",
  2738. token_usage_scope: "subagent_requests",
  2739. input_tokens: "8616",
  2740. output_tokens: "69",
  2741. cache_write_input_tokens: "5797",
  2742. total_tokens: "8685",
  2743. }),
  2744. }),
  2745. ]);
  2746. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toEqual([
  2747. expect.objectContaining({
  2748. messageId: "parent-command",
  2749. eventExtraDetail: expect.objectContaining({
  2750. request_time: "100",
  2751. duration_ms: "100",
  2752. agent_step_cnt: "1",
  2753. }),
  2754. }),
  2755. ]);
  2756. expect(
  2757. reportTelemetryEvent.mock.calls
  2758. .map(([payload]) => payload.elementName)
  2759. .filter(
  2760. (elementName) => elementName === "agent_step" || elementName === "message_completion",
  2761. ),
  2762. ).toEqual(["agent_step", "message_completion"]);
  2763. supervisor.handleFact({
  2764. ...commonFact("late-subagent-stopped", 6, "parent-session"),
  2765. sourceCommandId: "parent-command",
  2766. kind: "subagent.lifecycle",
  2767. phase: "stopped",
  2768. agentId: "agent-1",
  2769. childSessionId: "child-session",
  2770. parentToolCallId: "agent-tool",
  2771. background: false,
  2772. status: "failed",
  2773. });
  2774. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(1);
  2775. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(1);
  2776. supervisor.dispose();
  2777. });
  2778. it("background 仍上报 plan_request 和 seeded /report,但不产生 UI ARMS", async () => {
  2779. const { platform, reportTelemetryEvent, reportArmsCustomEvent } = createPlatform();
  2780. setUiPerfArmsReporter(platform);
  2781. let now = 10;
  2782. const supervisor = new ConversationTelemetrySupervisor({
  2783. platform,
  2784. workspaceScopeKey: "scope-background",
  2785. now: () => now,
  2786. });
  2787. supervisor.acceptPromptSeed({
  2788. sessionId: "session-1",
  2789. sourceCommandId: "command-1",
  2790. sendTime: 10,
  2791. extraDetail: {
  2792. ask_mode: "build",
  2793. model_name: "model",
  2794. model_provider: "provider",
  2795. },
  2796. });
  2797. supervisor.handleFact({
  2798. ...commonFact("background-start", 1),
  2799. kind: "turn.started",
  2800. });
  2801. now = 20;
  2802. supervisor.handleFact({
  2803. ...commonFact("background-model", 2),
  2804. kind: "model.request.status",
  2805. requestId: "request-bg",
  2806. status: "model_request_completed",
  2807. providerId: "provider",
  2808. modelId: "model",
  2809. transport: "fetch",
  2810. attempt: 1,
  2811. maxAttempts: 1,
  2812. durationMs: 5,
  2813. });
  2814. now = 30;
  2815. supervisor.handleFact({
  2816. ...commonFact("background-chunk", 3),
  2817. kind: "stream.chunk",
  2818. channel: "text",
  2819. chunkLength: 1,
  2820. firstChunk: true,
  2821. });
  2822. now = 40;
  2823. supervisor.handleFact({
  2824. ...commonFact("background-terminal", 4),
  2825. kind: "turn.terminal",
  2826. status: "success",
  2827. });
  2828. await supervisor.flushReportsForTest();
  2829. expect(reportsByElement(reportTelemetryEvent, "send_btn")).toHaveLength(1);
  2830. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(1);
  2831. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(1);
  2832. expect(reportArmsCustomEvent.mock.calls.map(([payload]) => payload.name)).toEqual([
  2833. "plan_request",
  2834. ]);
  2835. supervisor.dispose();
  2836. });
  2837. it("automation TurnStarted 自动建 seed,不伪造 send_btn,且调度字段只进入 completion", async () => {
  2838. const { platform, reportTelemetryEvent } = createPlatform();
  2839. const supervisor = new ConversationTelemetrySupervisor({
  2840. platform,
  2841. workspaceScopeKey: "scope-automation",
  2842. now: () => 1_700_000_000_500,
  2843. });
  2844. const sourceCommandId = "automation-1:1700000000000";
  2845. const automationFact = {
  2846. version: 1 as const,
  2847. eventSeq: 1,
  2848. occurredAt: 1_700_000_000_120,
  2849. sessionId: "session-automation",
  2850. sourceCommandId,
  2851. turnId: "turn-automation",
  2852. };
  2853. supervisor.handleFact({
  2854. ...automationFact,
  2855. eventId: "automation-start",
  2856. kind: "turn.started",
  2857. automationId: "automation-1",
  2858. taskTrigger: "schedule",
  2859. scheduledAt: 1_700_000_000_000,
  2860. });
  2861. supervisor.handleFact({
  2862. ...automationFact,
  2863. eventId: "automation-chunk",
  2864. eventSeq: 2,
  2865. kind: "stream.chunk",
  2866. channel: "text",
  2867. chunkLength: 2,
  2868. firstChunk: true,
  2869. });
  2870. supervisor.handleFact({
  2871. ...automationFact,
  2872. eventId: "automation-terminal",
  2873. eventSeq: 3,
  2874. kind: "turn.terminal",
  2875. status: "success",
  2876. });
  2877. await supervisor.flushReportsForTest();
  2878. expect(reportsByElement(reportTelemetryEvent, "send_btn")).toHaveLength(0);
  2879. const step = reportsByElement(reportTelemetryEvent, "agent_step")[0]?.eventExtraDetail;
  2880. expect(step).toMatchObject({
  2881. message_source: "scheduled_task",
  2882. task_trigger: "schedule",
  2883. automation_id: "automation-1",
  2884. });
  2885. expect(step).not.toHaveProperty("scheduled_at");
  2886. expect(step).not.toHaveProperty("schedule_lag_ms");
  2887. expect(
  2888. reportsByElement(reportTelemetryEvent, "message_completion")[0]?.eventExtraDetail,
  2889. ).toMatchObject({
  2890. message_source: "scheduled_task",
  2891. task_trigger: "schedule",
  2892. automation_id: "automation-1",
  2893. scheduled_at: "1700000000000",
  2894. schedule_lag_ms: "120",
  2895. });
  2896. supervisor.dispose();
  2897. });
  2898. it("manual run 不带调度字段;同会话后续 chat 轮不继承 automation_id、step 不携带 seed 模型维度", async () => {
  2899. const { platform, reportTelemetryEvent } = createPlatform();
  2900. const supervisor = new ConversationTelemetrySupervisor({
  2901. platform,
  2902. workspaceScopeKey: "scope-manual",
  2903. now: () => 1_700_000_001_000,
  2904. });
  2905. const manualCommandId = "automation-1:manual:run-1";
  2906. const manualFact = {
  2907. version: 1 as const,
  2908. occurredAt: 1_700_000_000_500,
  2909. sessionId: "session-shared",
  2910. sourceCommandId: manualCommandId,
  2911. turnId: "turn-manual",
  2912. };
  2913. supervisor.handleFact({
  2914. ...manualFact,
  2915. eventId: "manual-start",
  2916. eventSeq: 1,
  2917. kind: "turn.started",
  2918. automationId: "automation-1",
  2919. taskTrigger: "manual",
  2920. });
  2921. supervisor.handleFact({
  2922. ...manualFact,
  2923. eventId: "manual-chunk",
  2924. eventSeq: 2,
  2925. kind: "stream.chunk",
  2926. channel: "text",
  2927. chunkLength: 2,
  2928. firstChunk: true,
  2929. });
  2930. supervisor.handleFact({
  2931. ...manualFact,
  2932. eventId: "manual-terminal",
  2933. eventSeq: 3,
  2934. kind: "turn.terminal",
  2935. status: "success",
  2936. });
  2937. const chatCommandId = "command-chat-1";
  2938. supervisor.acceptPromptSeed({
  2939. sessionId: "session-shared",
  2940. sourceCommandId: chatCommandId,
  2941. sendTime: 1_700_000_000_900,
  2942. extraDetail: {
  2943. message_source: "chat",
  2944. task_trigger: "",
  2945. model_name: "seed-model",
  2946. plan_status: "coding_plan",
  2947. },
  2948. });
  2949. const chatFact = {
  2950. version: 1 as const,
  2951. occurredAt: 1_700_000_000_950,
  2952. sessionId: "session-shared",
  2953. sourceCommandId: chatCommandId,
  2954. turnId: "turn-chat",
  2955. };
  2956. supervisor.handleFact({
  2957. ...chatFact,
  2958. eventId: "chat-start",
  2959. eventSeq: 4,
  2960. kind: "turn.started",
  2961. });
  2962. supervisor.handleFact({
  2963. ...chatFact,
  2964. eventId: "chat-chunk",
  2965. eventSeq: 5,
  2966. kind: "stream.chunk",
  2967. channel: "text",
  2968. chunkLength: 2,
  2969. firstChunk: true,
  2970. });
  2971. supervisor.handleFact({
  2972. ...chatFact,
  2973. eventId: "chat-terminal",
  2974. eventSeq: 6,
  2975. kind: "turn.terminal",
  2976. status: "success",
  2977. });
  2978. await supervisor.flushReportsForTest();
  2979. expect(reportsByElement(reportTelemetryEvent, "send_btn")).toHaveLength(1);
  2980. const manualStep = reportsByElement(reportTelemetryEvent, "agent_step").find(
  2981. (payload) => payload.messageId === manualCommandId,
  2982. )?.eventExtraDetail;
  2983. expect(manualStep).toMatchObject({
  2984. message_source: "scheduled_task",
  2985. task_trigger: "manual",
  2986. automation_id: "automation-1",
  2987. });
  2988. expect(manualStep).not.toHaveProperty("scheduled_at");
  2989. const manualCompletion = reportsByElement(reportTelemetryEvent, "message_completion").find(
  2990. (payload) => payload.messageId === manualCommandId,
  2991. )?.eventExtraDetail;
  2992. expect(manualCompletion).toMatchObject({
  2993. message_source: "scheduled_task",
  2994. task_trigger: "manual",
  2995. automation_id: "automation-1",
  2996. });
  2997. expect(manualCompletion).not.toHaveProperty("scheduled_at");
  2998. expect(manualCompletion).not.toHaveProperty("schedule_lag_ms");
  2999. const chatStep = reportsByElement(reportTelemetryEvent, "agent_step").find(
  3000. (payload) => payload.messageId === chatCommandId,
  3001. )?.eventExtraDetail;
  3002. expect(chatStep).toMatchObject({ message_source: "chat", task_trigger: "" });
  3003. expect(chatStep).not.toHaveProperty("automation_id");
  3004. // seed 的模型/套餐维度只属于 send/completion,不进 step 契约。
  3005. expect(chatStep).not.toHaveProperty("plan_status");
  3006. const chatCompletion = reportsByElement(reportTelemetryEvent, "message_completion").find(
  3007. (payload) => payload.messageId === chatCommandId,
  3008. )?.eventExtraDetail;
  3009. expect(chatCompletion).toMatchObject({ message_source: "chat", task_trigger: "" });
  3010. expect(chatCompletion).not.toHaveProperty("automation_id");
  3011. supervisor.dispose();
  3012. });
  3013. it("Off-Peak first/resume/retry talk 共用 task 归因,manual 不继承且每轮 message_id 独立", async () => {
  3014. const { platform, reportTelemetryEvent } = createPlatform();
  3015. const supervisor = new ConversationTelemetrySupervisor({
  3016. platform,
  3017. workspaceScopeKey: "scope-off-peak",
  3018. now: () => 2_000,
  3019. });
  3020. let eventSeq = 0;
  3021. const runOffPeakTurn = (params: {
  3022. sessionId: string;
  3023. sourceCommandId: string;
  3024. turnId: string;
  3025. offPeakRunType: "init" | "resume";
  3026. }) => {
  3027. const base = {
  3028. version: 1 as const,
  3029. occurredAt: 1_000 + eventSeq,
  3030. sessionId: params.sessionId,
  3031. sourceCommandId: params.sourceCommandId,
  3032. turnId: params.turnId,
  3033. };
  3034. supervisor.handleFact({
  3035. ...base,
  3036. eventId: `${params.sourceCommandId}-start`,
  3037. eventSeq: eventSeq++,
  3038. kind: "turn.started",
  3039. offPeakTaskId: "offpeak-stable-1",
  3040. offPeakRunType: params.offPeakRunType,
  3041. });
  3042. supervisor.handleFact({
  3043. ...base,
  3044. eventId: `${params.sourceCommandId}-model`,
  3045. eventSeq: eventSeq++,
  3046. kind: "model.request.status",
  3047. requestId: `${params.sourceCommandId}-request`,
  3048. status: "model_request_started",
  3049. providerId: "runtime-provider",
  3050. modelId: "runtime-model",
  3051. providerHostname: "api.example.com",
  3052. transport: "fetch",
  3053. attempt: 1,
  3054. maxAttempts: 1,
  3055. });
  3056. supervisor.handleFact({
  3057. ...base,
  3058. eventId: `${params.sourceCommandId}-chunk`,
  3059. eventSeq: eventSeq++,
  3060. kind: "stream.chunk",
  3061. channel: "text",
  3062. chunkLength: 1,
  3063. firstChunk: true,
  3064. });
  3065. const terminal = {
  3066. ...base,
  3067. eventId: `${params.sourceCommandId}-terminal`,
  3068. eventSeq: eventSeq++,
  3069. kind: "turn.terminal",
  3070. status: "success",
  3071. } satisfies ConversationTelemetryFact;
  3072. supervisor.handleFact(terminal);
  3073. supervisor.handleFact({
  3074. ...terminal,
  3075. eventId: `${params.sourceCommandId}-terminal-duplicate`,
  3076. eventSeq: eventSeq++,
  3077. });
  3078. };
  3079. runOffPeakTurn({
  3080. sessionId: "talk-first",
  3081. sourceCommandId: "message-first",
  3082. turnId: "turn-first",
  3083. offPeakRunType: "init",
  3084. });
  3085. runOffPeakTurn({
  3086. sessionId: "talk-first",
  3087. sourceCommandId: "message-resume",
  3088. turnId: "turn-resume",
  3089. offPeakRunType: "resume",
  3090. });
  3091. runOffPeakTurn({
  3092. sessionId: "talk-retry",
  3093. sourceCommandId: "message-retry",
  3094. turnId: "turn-retry",
  3095. offPeakRunType: "init",
  3096. });
  3097. supervisor.acceptPromptSeed({
  3098. sessionId: "talk-first",
  3099. sourceCommandId: "message-manual",
  3100. sendTime: 1_500,
  3101. extraDetail: {
  3102. message_source: "chat",
  3103. task_trigger: "",
  3104. model_name: "manual-seed",
  3105. model_provider: "manual-provider",
  3106. },
  3107. });
  3108. supervisor.handleFact({
  3109. ...commonFact("manual-start", eventSeq++, "talk-first"),
  3110. sourceCommandId: "message-manual",
  3111. turnId: "turn-manual",
  3112. kind: "turn.started",
  3113. });
  3114. supervisor.handleFact({
  3115. ...commonFact("manual-chunk", eventSeq++, "talk-first"),
  3116. sourceCommandId: "message-manual",
  3117. turnId: "turn-manual",
  3118. kind: "stream.chunk",
  3119. channel: "text",
  3120. chunkLength: 1,
  3121. firstChunk: true,
  3122. });
  3123. supervisor.handleFact({
  3124. ...commonFact("manual-terminal", eventSeq++, "talk-first"),
  3125. sourceCommandId: "message-manual",
  3126. turnId: "turn-manual",
  3127. kind: "turn.terminal",
  3128. status: "success",
  3129. });
  3130. await supervisor.flushReportsForTest();
  3131. expect(reportsByElement(reportTelemetryEvent, "send_btn")).toHaveLength(1);
  3132. const completions = reportsByElement(reportTelemetryEvent, "message_completion");
  3133. const steps = reportsByElement(reportTelemetryEvent, "agent_step");
  3134. expect(completions).toHaveLength(4);
  3135. for (const [messageId, offPeakRunType] of [
  3136. ["message-first", "init"],
  3137. ["message-resume", "resume"],
  3138. ["message-retry", "init"],
  3139. ] as const) {
  3140. const detail = completions.find(
  3141. (payload) => payload.messageId === messageId,
  3142. )?.eventExtraDetail;
  3143. expect(detail).toMatchObject({
  3144. message_source: "off_peak_task",
  3145. off_peak_task_id: "offpeak-stable-1",
  3146. off_peak_run_type: offPeakRunType,
  3147. model_name: "runtime-provider/runtime-model",
  3148. model_provider: "runtime-provider",
  3149. });
  3150. expect(detail).not.toHaveProperty("automation_id");
  3151. expect(detail).not.toHaveProperty("task_trigger");
  3152. expect(
  3153. steps.find((payload) => payload.messageId === messageId)?.eventExtraDetail,
  3154. ).toMatchObject({
  3155. message_source: "off_peak_task",
  3156. off_peak_task_id: "offpeak-stable-1",
  3157. off_peak_run_type: offPeakRunType,
  3158. });
  3159. }
  3160. expect(completions.find((payload) => payload.messageId === "message-retry")?.talkId).toBe(
  3161. "talk-retry",
  3162. );
  3163. const manual = completions.find(
  3164. (payload) => payload.messageId === "message-manual",
  3165. )?.eventExtraDetail;
  3166. expect(manual).toMatchObject({ message_source: "chat" });
  3167. expect(manual).not.toHaveProperty("off_peak_task_id");
  3168. expect(manual).not.toHaveProperty("off_peak_run_type");
  3169. const manualStep = steps.find(
  3170. (payload) => payload.messageId === "message-manual",
  3171. )?.eventExtraDetail;
  3172. expect(manualStep).not.toHaveProperty("off_peak_task_id");
  3173. expect(manualStep).not.toHaveProperty("off_peak_run_type");
  3174. supervisor.dispose();
  3175. });
  3176. it("Off-Peak usage fact 去重后 completion 保留精确总量,step 保持占位口径", async () => {
  3177. const { platform, reportTelemetryEvent } = createPlatform();
  3178. const supervisor = new ConversationTelemetrySupervisor({
  3179. platform,
  3180. workspaceScopeKey: "scope-off-peak-usage",
  3181. now: () => 2_000,
  3182. });
  3183. const base = {
  3184. version: 1 as const,
  3185. occurredAt: 1_000,
  3186. sessionId: "talk-usage",
  3187. sourceCommandId: "message-usage",
  3188. turnId: "turn-usage",
  3189. };
  3190. supervisor.handleFact({
  3191. ...base,
  3192. eventId: "usage-start",
  3193. eventSeq: 1,
  3194. kind: "turn.started",
  3195. offPeakTaskId: "offpeak-usage",
  3196. });
  3197. const usage = {
  3198. ...base,
  3199. eventId: "usage-once",
  3200. eventSeq: 2,
  3201. kind: "usage.delta",
  3202. inputTokens: 10,
  3203. outputTokens: 5,
  3204. totalTokens: 18,
  3205. reasoningTokens: 3,
  3206. cacheReadTokens: 2,
  3207. cacheWriteTokens: 1,
  3208. } satisfies ConversationTelemetryFact;
  3209. supervisor.handleFact(usage);
  3210. supervisor.handleFact(usage);
  3211. supervisor.handleFact({
  3212. ...base,
  3213. eventId: "usage-chunk",
  3214. eventSeq: 3,
  3215. kind: "stream.chunk",
  3216. channel: "text",
  3217. chunkLength: 1,
  3218. firstChunk: true,
  3219. });
  3220. supervisor.handleFact({
  3221. ...base,
  3222. eventId: "usage-terminal",
  3223. eventSeq: 4,
  3224. kind: "turn.terminal",
  3225. status: "success",
  3226. });
  3227. await supervisor.flushReportsForTest();
  3228. expect(
  3229. reportsByElement(reportTelemetryEvent, "message_completion")[0]?.eventExtraDetail,
  3230. ).toMatchObject({
  3231. input_tokens: "10",
  3232. output_tokens: "5",
  3233. reasoning_tokens: "3",
  3234. total_tokens: "18",
  3235. off_peak_task_id: "offpeak-usage",
  3236. });
  3237. expect(reportsByElement(reportTelemetryEvent, "agent_step")[0]?.eventExtraDetail).toMatchObject(
  3238. {
  3239. input_tokens: "0",
  3240. output_tokens: "0",
  3241. cached_tokens: "0",
  3242. off_peak_task_id: "offpeak-usage",
  3243. },
  3244. );
  3245. supervisor.dispose();
  3246. });
  3247. it("CronCreate 成功终态把新任务 automation_id 写入对应 agent_step", async () => {
  3248. const { platform, reportTelemetryEvent } = createPlatform();
  3249. const supervisor = new ConversationTelemetrySupervisor({
  3250. platform,
  3251. workspaceScopeKey: "scope-cron-create",
  3252. now: () => 500,
  3253. });
  3254. supervisor.acceptPromptSeed({
  3255. sessionId: "session-cron-create",
  3256. sourceCommandId: "command-cron-create",
  3257. sendTime: 100,
  3258. extraDetail: { message_source: "chat", task_trigger: "" },
  3259. });
  3260. const base = {
  3261. version: 1 as const,
  3262. sessionId: "session-cron-create",
  3263. sourceCommandId: "command-cron-create",
  3264. turnId: "turn-cron-create",
  3265. };
  3266. supervisor.handleFact({
  3267. ...base,
  3268. eventId: "cron-turn-start",
  3269. eventSeq: 1,
  3270. occurredAt: 110,
  3271. kind: "turn.started",
  3272. });
  3273. supervisor.handleFact({
  3274. ...base,
  3275. eventId: "cron-tool-start",
  3276. eventSeq: 2,
  3277. occurredAt: 120,
  3278. kind: "tool.lifecycle",
  3279. phase: "started",
  3280. toolCallId: "tool-cron-create",
  3281. toolName: "CronCreate",
  3282. });
  3283. supervisor.handleFact({
  3284. ...base,
  3285. eventId: "cron-tool-complete",
  3286. eventSeq: 3,
  3287. occurredAt: 150,
  3288. kind: "tool.lifecycle",
  3289. phase: "completed",
  3290. toolCallId: "tool-cron-create",
  3291. toolName: "CronCreate",
  3292. automationId: "automation-created",
  3293. });
  3294. await supervisor.flushReportsForTest();
  3295. expect(reportsByElement(reportTelemetryEvent, "agent_step")[0]?.eventExtraDetail).toMatchObject(
  3296. {
  3297. tool_name: "CronCreate",
  3298. status: "success",
  3299. automation_id: "automation-created",
  3300. },
  3301. );
  3302. supervisor.dispose();
  3303. });
  3304. it("异步 reporter 仍严格按 send → step → completion 串行", async () => {
  3305. const { platform, reportTelemetryEvent } = createPlatform();
  3306. const releases: Array<() => void> = [];
  3307. reportTelemetryEvent.mockImplementation(
  3308. () => new Promise<void>((resolve) => releases.push(resolve)),
  3309. );
  3310. const supervisor = new ConversationTelemetrySupervisor({
  3311. platform,
  3312. workspaceScopeKey: "scope-report-order",
  3313. now: () => 100,
  3314. });
  3315. supervisor.acceptPromptSeed({
  3316. sessionId: "session-1",
  3317. sourceCommandId: "command-1",
  3318. sendTime: 10,
  3319. extraDetail: { model_name: "model", model_provider: "provider" },
  3320. });
  3321. supervisor.handleFact({
  3322. ...commonFact("order-start", 1),
  3323. kind: "turn.started",
  3324. });
  3325. supervisor.handleFact({
  3326. ...commonFact("order-model", 2),
  3327. kind: "model.request.status",
  3328. requestId: "request-1",
  3329. status: "model_request_started",
  3330. providerId: "provider",
  3331. modelId: "model",
  3332. transport: "fetch",
  3333. attempt: 1,
  3334. maxAttempts: 1,
  3335. });
  3336. supervisor.handleFact({
  3337. ...commonFact("order-chunk", 3),
  3338. kind: "stream.chunk",
  3339. channel: "text",
  3340. chunkLength: 1,
  3341. firstChunk: true,
  3342. });
  3343. supervisor.handleFact({
  3344. ...commonFact("order-terminal", 4),
  3345. kind: "turn.terminal",
  3346. status: "success",
  3347. });
  3348. const reportedNames = () =>
  3349. reportTelemetryEvent.mock.calls.map(([payload]) => payload.elementName);
  3350. expect(reportedNames()).toEqual(["send_btn"]);
  3351. releases.shift()?.();
  3352. await vi.waitFor(() => expect(reportedNames()).toEqual(["send_btn", "agent_step"]));
  3353. releases.shift()?.();
  3354. await vi.waitFor(() =>
  3355. expect(reportedNames()).toEqual(["send_btn", "agent_step", "message_completion"]),
  3356. );
  3357. releases.shift()?.();
  3358. await supervisor.flushReportsForTest();
  3359. supervisor.dispose();
  3360. });
  3361. it("ACK 前 buffer 保留 turn.started,并按 terminal key exactly-once", async () => {
  3362. const { platform, reportTelemetryEvent, reportArmsCustomEvent } = createPlatform();
  3363. setUiPerfArmsReporter(platform);
  3364. let now = 1_000;
  3365. const supervisor = new ConversationTelemetrySupervisor({
  3366. platform,
  3367. workspaceScopeKey: "scope-buffer",
  3368. now: () => now,
  3369. });
  3370. supervisor.handleFact({
  3371. ...commonFact("buffer-start", 1),
  3372. kind: "turn.started",
  3373. });
  3374. for (let index = 0; index < 140; index += 1) {
  3375. now += 1;
  3376. supervisor.handleFact({
  3377. ...commonFact(`buffer-chunk-${index}`, index + 2),
  3378. kind: "stream.chunk",
  3379. channel: "text",
  3380. chunkLength: 1,
  3381. firstChunk: index === 0,
  3382. });
  3383. }
  3384. supervisor.acceptPromptSeed({
  3385. sessionId: "session-1",
  3386. sourceCommandId: "command-1",
  3387. sendTime: 900,
  3388. extraDetail: {
  3389. model_name: "model",
  3390. model_provider: "provider",
  3391. },
  3392. });
  3393. supervisor.attachForeground({}, "session-1");
  3394. now = 2_000;
  3395. const terminal = {
  3396. ...commonFact("buffer-terminal-1", 200),
  3397. kind: "turn.terminal",
  3398. status: "interrupted",
  3399. resultType: "cancelled",
  3400. errorCode: "USER_INTERRUPT",
  3401. errorMessage: "stopped",
  3402. } satisfies ConversationTelemetryFact;
  3403. supervisor.handleFact(terminal);
  3404. supervisor.handleFact({ ...terminal, eventId: "buffer-terminal-2", eventSeq: 201 });
  3405. await supervisor.flushReportsForTest();
  3406. const completion = reportsByElement(reportTelemetryEvent, "message_completion");
  3407. expect(completion).toHaveLength(1);
  3408. expect(completion[0]).toMatchObject({
  3409. talkId: "session-1",
  3410. messageId: "command-1",
  3411. eventExtraDetail: {
  3412. status: "user_interrupt",
  3413. error_type: "USER_INTERRUPT",
  3414. error_msg: "[redacted]",
  3415. time_to_first_token: "101",
  3416. },
  3417. });
  3418. // buffered chunk 到达时仍在 background;terminal 前切回也不能补造 UI TTFT。
  3419. expect(armsByName(reportArmsCustomEvent, "perf_ui_first_token")).toHaveLength(0);
  3420. expect(armsByName(reportArmsCustomEvent, "plan_ttft")).toHaveLength(0);
  3421. expect(reportsByElement(reportTelemetryEvent, "agent_step")[0]).toMatchObject({
  3422. eventExtraDetail: { status: "success" },
  3423. });
  3424. supervisor.dispose();
  3425. });
  3426. it("同 session direct 与 queued seed 依次 promotion,terminal 不清后续队列", async () => {
  3427. const { platform, reportTelemetryEvent } = createPlatform();
  3428. let now = 100;
  3429. const supervisor = new ConversationTelemetrySupervisor({
  3430. platform,
  3431. workspaceScopeKey: "scope-queued",
  3432. now: () => now,
  3433. });
  3434. for (const sourceCommandId of ["command-direct", "command-queued"]) {
  3435. supervisor.acceptPromptSeed({
  3436. sessionId: "session-queued",
  3437. sourceCommandId,
  3438. sendTime: now,
  3439. extraDetail: { model_name: "model", model_provider: "provider" },
  3440. });
  3441. now += 10;
  3442. }
  3443. supervisor.handleFact({
  3444. ...commonFact("direct-start", 1, "session-queued"),
  3445. sourceCommandId: "command-direct",
  3446. turnId: "turn-direct",
  3447. kind: "turn.started",
  3448. });
  3449. now = 200;
  3450. supervisor.handleFact({
  3451. ...commonFact("direct-terminal", 2, "session-queued"),
  3452. sourceCommandId: "command-direct",
  3453. turnId: "turn-direct",
  3454. kind: "turn.terminal",
  3455. status: "success",
  3456. });
  3457. now = 300;
  3458. supervisor.handleFact({
  3459. ...commonFact("queued-start", 3, "session-queued"),
  3460. sourceCommandId: "command-queued",
  3461. turnId: "turn-queued",
  3462. kind: "turn.started",
  3463. });
  3464. now = 400;
  3465. supervisor.handleFact({
  3466. ...commonFact("queued-terminal", 4, "session-queued"),
  3467. sourceCommandId: "command-queued",
  3468. turnId: "turn-queued",
  3469. kind: "turn.terminal",
  3470. status: "success",
  3471. });
  3472. await supervisor.flushReportsForTest();
  3473. expect(reportsByElement(reportTelemetryEvent, "send_btn")).toHaveLength(2);
  3474. expect(
  3475. reportsByElement(reportTelemetryEvent, "message_completion").map(
  3476. (payload) => payload.messageId,
  3477. ),
  3478. ).toEqual(["command-direct", "command-queued"]);
  3479. supervisor.dispose();
  3480. });
  3481. it("无本地 seed 的 command fact 使用 200 组 LRU 上限", async () => {
  3482. const { platform, reportTelemetryEvent } = createPlatform();
  3483. const supervisor = new ConversationTelemetrySupervisor({
  3484. platform,
  3485. workspaceScopeKey: "scope-pending-lru",
  3486. now: () => 1_000,
  3487. });
  3488. for (let index = 0; index < 200; index += 1) {
  3489. supervisor.handleFact({
  3490. ...commonFact(`pending-${index}`, index, `session-${index}`),
  3491. sourceCommandId: `command-${index}`,
  3492. turnId: `turn-${index}`,
  3493. kind: "turn.started",
  3494. });
  3495. }
  3496. // 再命中 command-0,把它移到 LRU 尾部;新增 command-200 应淘汰 command-1。
  3497. supervisor.handleFact({
  3498. ...commonFact("pending-0-touch", 201, "session-0"),
  3499. sourceCommandId: "command-0",
  3500. turnId: "turn-0",
  3501. kind: "stream.chunk",
  3502. channel: "text",
  3503. chunkLength: 1,
  3504. firstChunk: true,
  3505. });
  3506. supervisor.handleFact({
  3507. ...commonFact("pending-200", 202, "session-200"),
  3508. sourceCommandId: "command-200",
  3509. turnId: "turn-200",
  3510. kind: "turn.started",
  3511. });
  3512. expect(supervisor.getPendingCommandCountForTest()).toBe(200);
  3513. supervisor.acceptPromptSeed({
  3514. sessionId: "session-1",
  3515. sourceCommandId: "command-1",
  3516. sendTime: 900,
  3517. extraDetail: {},
  3518. });
  3519. supervisor.handleFact({
  3520. ...commonFact("evicted-terminal", 203, "session-1"),
  3521. sourceCommandId: "command-1",
  3522. turnId: "turn-1",
  3523. kind: "turn.terminal",
  3524. status: "success",
  3525. });
  3526. supervisor.acceptPromptSeed({
  3527. sessionId: "session-0",
  3528. sourceCommandId: "command-0",
  3529. sendTime: 900,
  3530. extraDetail: {},
  3531. });
  3532. supervisor.handleFact({
  3533. ...commonFact("retained-terminal", 204, "session-0"),
  3534. sourceCommandId: "command-0",
  3535. turnId: "turn-0",
  3536. kind: "turn.terminal",
  3537. status: "success",
  3538. });
  3539. await supervisor.flushReportsForTest();
  3540. expect(
  3541. reportsByElement(reportTelemetryEvent, "message_completion").map(
  3542. (payload) => payload.messageId,
  3543. ),
  3544. ).toEqual(["command-0"]);
  3545. supervisor.dispose();
  3546. });
  3547. it("foreground raw 负 TTFT 仅由 ui_perf 钳 0,plan_ttft 丢弃", () => {
  3548. const { platform, reportArmsCustomEvent } = createPlatform();
  3549. setUiPerfArmsReporter(platform);
  3550. let now = 200;
  3551. const supervisor = new ConversationTelemetrySupervisor({
  3552. platform,
  3553. workspaceScopeKey: "scope-clock-rollback",
  3554. now: () => now,
  3555. });
  3556. supervisor.attachForeground({}, "session-1");
  3557. supervisor.acceptPromptSeed({
  3558. sessionId: "session-1",
  3559. sourceCommandId: "command-1",
  3560. sendTime: 200,
  3561. extraDetail: { model_name: "model", model_provider: "provider" },
  3562. });
  3563. supervisor.handleFact({
  3564. ...commonFact("rollback-start", 1),
  3565. kind: "turn.started",
  3566. });
  3567. now = 100;
  3568. supervisor.handleFact({
  3569. ...commonFact("rollback-token", 2),
  3570. kind: "stream.chunk",
  3571. channel: "text",
  3572. chunkLength: 1,
  3573. firstChunk: true,
  3574. });
  3575. now = 300;
  3576. supervisor.handleFact({
  3577. ...commonFact("rollback-terminal", 3),
  3578. kind: "turn.terminal",
  3579. status: "success",
  3580. });
  3581. expect(armsByName(reportArmsCustomEvent, "perf_ui_first_token")[0]?.value).toBe(0);
  3582. expect(armsByName(reportArmsCustomEvent, "plan_ttft")).toHaveLength(0);
  3583. supervisor.dispose();
  3584. });
  3585. it("plan_request 五态无需 seed,compaction 按到达时 foreground 与 operation 去重", () => {
  3586. const { platform, reportTelemetryEvent, reportArmsCustomEvent } = createPlatform();
  3587. const supervisor = new ConversationTelemetrySupervisor({
  3588. platform,
  3589. workspaceScopeKey: "scope-independent",
  3590. now: () => 2_000,
  3591. });
  3592. const statuses = [
  3593. "model_request_started",
  3594. "model_request_completed",
  3595. "model_request_failed",
  3596. "model_retry_scheduled",
  3597. "model_stream_stalled",
  3598. ] as const;
  3599. statuses.forEach((status, index) => {
  3600. supervisor.handleFact({
  3601. ...commonFact(`plan-${index}`, index, "session-plan"),
  3602. sourceCommandId: undefined,
  3603. turnId: undefined,
  3604. kind: "model.request.status",
  3605. requestId: "request-plan",
  3606. status,
  3607. providerId: "provider",
  3608. modelId: "model",
  3609. transport: "fetch",
  3610. attempt: 1,
  3611. maxAttempts: 3,
  3612. });
  3613. });
  3614. expect(
  3615. armsByName(reportArmsCustomEvent, "plan_request").map(
  3616. (payload) => payload.properties?.request_status,
  3617. ),
  3618. ).toEqual(["started", "completed", "failed", "retry_scheduled", "stream_stalled"]);
  3619. const compaction = {
  3620. ...commonFact("compact-1", 20, "session-compact"),
  3621. sourceCommandId: undefined,
  3622. turnId: undefined,
  3623. kind: "compaction.terminal",
  3624. operationId: "operation-1",
  3625. summaryMessageId: "summary-1",
  3626. status: "completed",
  3627. trigger: "manual",
  3628. reason: "manual request",
  3629. attempt: 2,
  3630. startedAt: 1_000,
  3631. endedAt: 1_500,
  3632. preCompactTokenCount: 100,
  3633. postCompactTokenCount: 40,
  3634. truePostCompactTokenCount: 35,
  3635. modelName: "model",
  3636. modelProvider: "provider",
  3637. } satisfies ConversationTelemetryFact;
  3638. supervisor.handleFact(compaction);
  3639. expect(reportsByElement(reportTelemetryEvent, "context_compaction")).toHaveLength(0);
  3640. supervisor.attachForeground({}, "session-compact");
  3641. supervisor.handleFact({ ...compaction, eventId: "compact-2", eventSeq: 21 });
  3642. supervisor.handleFact({ ...compaction, eventId: "compact-3", eventSeq: 22 });
  3643. expect(reportsByElement(reportTelemetryEvent, "context_compaction")).toHaveLength(0);
  3644. const foregroundCompaction = {
  3645. ...compaction,
  3646. eventId: "compact-4",
  3647. eventSeq: 23,
  3648. operationId: "operation-2",
  3649. summaryMessageId: "summary-2",
  3650. } satisfies ConversationTelemetryFact;
  3651. supervisor.handleFact(foregroundCompaction);
  3652. supervisor.handleFact({
  3653. ...foregroundCompaction,
  3654. eventId: "compact-5",
  3655. eventSeq: 24,
  3656. status: "failed",
  3657. reason: "late contradictory terminal",
  3658. });
  3659. expect(reportsByElement(reportTelemetryEvent, "context_compaction")).toEqual([
  3660. expect.objectContaining({
  3661. elementName: "context_compaction",
  3662. eventRegion: "app",
  3663. eventType: "agent_trace",
  3664. talkId: "session-compact",
  3665. messageId: "summary-2",
  3666. eventExtraDetail: {
  3667. status: "completed",
  3668. trigger: "manual",
  3669. reason: "manual request",
  3670. attempt: "2",
  3671. duration_ms: "500",
  3672. pre_compact_tokens: "100",
  3673. post_compact_tokens: "40",
  3674. true_post_compact_tokens: "35",
  3675. compact_ratio: "0.4000",
  3676. model_name: "provider/model",
  3677. model_provider: "provider",
  3678. },
  3679. }),
  3680. ]);
  3681. supervisor.dispose();
  3682. });
  3683. it("compaction 不用 compactReason 回填旧 reason,glm 模型保持原值", () => {
  3684. const { platform, reportTelemetryEvent } = createPlatform();
  3685. const supervisor = new ConversationTelemetrySupervisor({
  3686. platform,
  3687. workspaceScopeKey: "scope-compact-legacy-fields",
  3688. now: () => 2_000,
  3689. });
  3690. supervisor.attachForeground({}, "session-compact");
  3691. supervisor.handleFact({
  3692. ...commonFact("compact-legacy", 1, "session-compact"),
  3693. sourceCommandId: undefined,
  3694. turnId: undefined,
  3695. kind: "compaction.terminal",
  3696. operationId: "operation-legacy",
  3697. status: "completed",
  3698. trigger: "auto",
  3699. compactReason: "context_limit",
  3700. modelName: "glm-model",
  3701. modelProvider: "glm",
  3702. });
  3703. expect(reportsByElement(reportTelemetryEvent, "context_compaction")[0]).toMatchObject({
  3704. eventExtraDetail: {
  3705. reason: "",
  3706. model_name: "glm-model",
  3707. model_provider: "glm",
  3708. },
  3709. });
  3710. supervisor.dispose();
  3711. });
  3712. it("tool-first 与无 token terminal 保留旧 first-token ARMS 边界", () => {
  3713. const { platform, reportArmsCustomEvent } = createPlatform();
  3714. setUiPerfArmsReporter(platform);
  3715. let now = 100;
  3716. const supervisor = new ConversationTelemetrySupervisor({
  3717. platform,
  3718. workspaceScopeKey: "scope-tool-first",
  3719. now: () => now,
  3720. });
  3721. supervisor.attachForeground({}, "session-1");
  3722. supervisor.acceptPromptSeed({
  3723. sessionId: "session-1",
  3724. sourceCommandId: "command-1",
  3725. sendTime: 100,
  3726. extraDetail: { model_name: "model", model_provider: "provider" },
  3727. });
  3728. supervisor.handleFact({ ...commonFact("tool-first-start", 1), kind: "turn.started" });
  3729. now = 140;
  3730. supervisor.handleFact({
  3731. ...commonFact("tool-first-tool", 2),
  3732. kind: "tool.lifecycle",
  3733. phase: "scheduled",
  3734. toolCallId: "tool-1",
  3735. toolName: "Read",
  3736. });
  3737. now = 200;
  3738. supervisor.handleFact({
  3739. ...commonFact("tool-first-terminal", 3),
  3740. kind: "turn.terminal",
  3741. status: "success",
  3742. });
  3743. expect(armsByName(reportArmsCustomEvent, "perf_ui_first_token")[0]?.value).toBe(40);
  3744. expect(armsByName(reportArmsCustomEvent, "plan_ttft")[0]?.value).toBe(40);
  3745. supervisor.acceptPromptSeed({
  3746. sessionId: "session-2",
  3747. sourceCommandId: "command-2",
  3748. sendTime: 200,
  3749. extraDetail: { model_name: "model", model_provider: "provider" },
  3750. });
  3751. supervisor.attachForeground({}, "session-2");
  3752. supervisor.handleFact({
  3753. ...commonFact("no-token-start", 4, "session-2"),
  3754. sourceCommandId: "command-2",
  3755. turnId: "turn-2",
  3756. kind: "turn.started",
  3757. });
  3758. now = 260;
  3759. supervisor.handleFact({
  3760. ...commonFact("no-token-terminal", 5, "session-2"),
  3761. sourceCommandId: "command-2",
  3762. turnId: "turn-2",
  3763. kind: "turn.terminal",
  3764. status: "success",
  3765. });
  3766. expect(
  3767. armsByName(reportArmsCustomEvent, "perf_ui_first_token").map((item) => item.value),
  3768. ).toEqual([40, 0]);
  3769. expect(armsByName(reportArmsCustomEvent, "plan_ttft")).toHaveLength(1);
  3770. supervisor.dispose();
  3771. });
  3772. it("parented child text 不进入 generation,但保留旧 TTFT 与 stall", async () => {
  3773. const { platform, reportTelemetryEvent, reportArmsCustomEvent } = createPlatform();
  3774. setUiPerfArmsReporter(platform);
  3775. let now = 100;
  3776. const supervisor = new ConversationTelemetrySupervisor({
  3777. platform,
  3778. workspaceScopeKey: "scope-parented-child",
  3779. now: () => now,
  3780. });
  3781. supervisor.attachForeground({}, "session-1");
  3782. supervisor.acceptPromptSeed({
  3783. sessionId: "session-1",
  3784. sourceCommandId: "command-1",
  3785. sendTime: 100,
  3786. extraDetail: { model_name: "model", model_provider: "provider" },
  3787. });
  3788. supervisor.handleFact({ ...commonFact("child-start", 1), kind: "turn.started" });
  3789. now = 150;
  3790. supervisor.handleFact({
  3791. ...commonFact("child-chunk-1", 2),
  3792. kind: "stream.chunk",
  3793. channel: "text",
  3794. chunkLength: 10,
  3795. firstChunk: true,
  3796. parentToolCallId: "parent-agent-tool",
  3797. });
  3798. now = 3_251;
  3799. supervisor.handleFact({
  3800. ...commonFact("child-chunk-2", 3),
  3801. kind: "stream.chunk",
  3802. channel: "text",
  3803. chunkLength: 10,
  3804. firstChunk: false,
  3805. parentToolCallId: "parent-agent-tool",
  3806. });
  3807. now = 3_300;
  3808. supervisor.handleFact({
  3809. ...commonFact("child-terminal", 4),
  3810. kind: "turn.terminal",
  3811. status: "success",
  3812. });
  3813. await supervisor.flushReportsForTest();
  3814. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(0);
  3815. expect(armsByName(reportArmsCustomEvent, "perf_ui_stream_stall")[0]?.value).toBe(3_101);
  3816. expect(armsByName(reportArmsCustomEvent, "perf_ui_first_token")[0]?.value).toBe(50);
  3817. expect(armsByName(reportArmsCustomEvent, "plan_ttft")[0]?.value).toBe(50);
  3818. supervisor.dispose();
  3819. });
  3820. it("parented child thought 保留旧 reasoning 与 TTFT 行为", async () => {
  3821. const { platform, reportTelemetryEvent, reportArmsCustomEvent } = createPlatform();
  3822. setUiPerfArmsReporter(platform);
  3823. let now = 100;
  3824. const supervisor = new ConversationTelemetrySupervisor({
  3825. platform,
  3826. workspaceScopeKey: "scope-parented-thought",
  3827. now: () => now,
  3828. });
  3829. supervisor.attachForeground({}, "session-1");
  3830. supervisor.acceptPromptSeed({
  3831. sessionId: "session-1",
  3832. sourceCommandId: "command-1",
  3833. sendTime: 100,
  3834. extraDetail: { model_name: "model", model_provider: "provider" },
  3835. });
  3836. supervisor.handleFact({ ...commonFact("thought-start", 1), kind: "turn.started" });
  3837. now = 150;
  3838. supervisor.handleFact({
  3839. ...commonFact("parented-thought", 2),
  3840. kind: "stream.chunk",
  3841. channel: "thought",
  3842. chunkLength: 10,
  3843. firstChunk: true,
  3844. parentToolCallId: "parent-agent-tool",
  3845. });
  3846. now = 200;
  3847. supervisor.handleFact({
  3848. ...commonFact("thought-terminal", 3),
  3849. kind: "turn.terminal",
  3850. status: "success",
  3851. });
  3852. await supervisor.flushReportsForTest();
  3853. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(1);
  3854. expect(armsByName(reportArmsCustomEvent, "perf_ui_first_token")[0]?.value).toBe(50);
  3855. expect(armsByName(reportArmsCustomEvent, "plan_ttft")[0]?.value).toBe(50);
  3856. supervisor.dispose();
  3857. });
  3858. it("chat_error_banner 复用既有 builder 上报真实可见错误", () => {
  3859. const { platform, reportArmsCustomEvent } = createPlatform();
  3860. const supervisor = new ConversationTelemetrySupervisor({
  3861. platform,
  3862. workspaceScopeKey: "scope-error",
  3863. });
  3864. supervisor.reportVisibleChatError({
  3865. errorKey: "error-1",
  3866. displayMessage: "Request failed",
  3867. error: {
  3868. message: "raw request failed",
  3869. code: "MODEL_ERROR",
  3870. traceId: "trace-1",
  3871. taskId: "session-1",
  3872. detail: "detail",
  3873. },
  3874. });
  3875. expect(armsByName(reportArmsCustomEvent, "chat_error_banner")).toEqual([
  3876. {
  3877. name: "chat_error_banner",
  3878. group: "ui_error",
  3879. value: 1,
  3880. properties: expect.objectContaining({
  3881. surface: "chat_input_error_banner",
  3882. error_code: "MODEL_ERROR",
  3883. error_message: "Request failed",
  3884. trace_id: "trace-1",
  3885. task_id: "session-1",
  3886. has_detail: true,
  3887. provider_business_action: "",
  3888. provider_business_code: "",
  3889. }),
  3890. },
  3891. ]);
  3892. supervisor.dispose();
  3893. });
  3894. it("chat_error_banner 保留普通业务恢复维度并隐藏 3007 内部动作", () => {
  3895. const { platform, reportArmsCustomEvent } = createPlatform();
  3896. const supervisor = new ConversationTelemetrySupervisor({
  3897. platform,
  3898. workspaceScopeKey: "scope-provider-errors",
  3899. });
  3900. supervisor.reportVisibleChatError({
  3901. displayMessage: "Please login",
  3902. error: { message: "login required", code: "1006" },
  3903. });
  3904. supervisor.reportVisibleChatError({
  3905. displayMessage: "Security check rejected",
  3906. error: { message: "security check rejected", code: "3007" },
  3907. });
  3908. expect(
  3909. armsByName(reportArmsCustomEvent, "chat_error_banner").map((payload) => payload.properties),
  3910. ).toEqual([
  3911. expect.objectContaining({
  3912. provider_business_action: "login",
  3913. provider_business_code: "1006",
  3914. }),
  3915. expect.objectContaining({
  3916. provider_business_action: "",
  3917. provider_business_code: "",
  3918. }),
  3919. ]);
  3920. supervisor.dispose();
  3921. });
  3922. });
  3923. describe("workflow subagent:动态工作流子代理的 token 埋点(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Token telemetry for subagents」)", () => {
  3924. const CHILD = "sess_dwf-run-1-worker_1";
  3925. function spawnWorkflowActor(
  3926. supervisor: ConversationTelemetrySupervisor,
  3927. input: { sourceCommandId?: string; childSessionId?: string; agentId?: string } = {},
  3928. ) {
  3929. supervisor.handleFact({
  3930. ...commonFact("wf-actor-spawned", 1, "parent-session"),
  3931. ...(input.sourceCommandId === undefined
  3932. ? { sourceCommandId: "launch-input-1" }
  3933. : { sourceCommandId: input.sourceCommandId }),
  3934. kind: "workflow.lifecycle",
  3935. phase: "actor-spawned",
  3936. runId: "dwfrun-1",
  3937. toolCallId: "tool-wf",
  3938. agentId: input.agentId ?? "worker@1",
  3939. childSessionId: input.childSessionId ?? CHILD,
  3940. });
  3941. }
  3942. function childUsage(
  3943. supervisor: ConversationTelemetrySupervisor,
  3944. eventId: string,
  3945. requestId: string,
  3946. ) {
  3947. supervisor.handleFact({
  3948. ...commonFact(`${eventId}-request`, 1, CHILD),
  3949. turnId: "child-turn-1",
  3950. kind: "model.request.status",
  3951. requestId,
  3952. status: "model_request_started",
  3953. providerId: "glm-provider",
  3954. modelId: "glm-5.3",
  3955. providerHostname: "glm.example.com",
  3956. transport: "sse",
  3957. querySource: "workflow_child",
  3958. attempt: 1,
  3959. maxAttempts: 1,
  3960. });
  3961. supervisor.handleFact({
  3962. ...commonFact(eventId, 2, CHILD),
  3963. turnId: "child-turn-1",
  3964. kind: "usage.delta",
  3965. requestId,
  3966. providerId: "glm-provider",
  3967. modelId: "glm-5.3",
  3968. providerHostname: "glm.example.com",
  3969. inputTokens: 1000,
  3970. outputTokens: 50,
  3971. totalTokens: 1050,
  3972. reasoningTokens: 0,
  3973. cacheReadTokens: 0,
  3974. cacheWriteTokens: 0,
  3975. });
  3976. }
  3977. function settleRun(
  3978. supervisor: ConversationTelemetrySupervisor,
  3979. status: "completed" | "errored" | "stopped",
  3980. errorMessage?: string,
  3981. ) {
  3982. supervisor.handleFact({
  3983. ...commonFact("wf-run-settled", 9, "parent-session"),
  3984. sourceCommandId: "launch-input-1",
  3985. kind: "workflow.lifecycle",
  3986. phase: "run-settled",
  3987. runId: "dwfrun-1",
  3988. toolCallId: "tool-wf",
  3989. status,
  3990. ...(errorMessage === undefined ? {} : { errorMessage }),
  3991. });
  3992. }
  3993. it("工具 step 零 token 带角色与 run 字段;usage 按 requestId 去重;子会话 turn.terminal 不结算;run-settled 一条汇总 step", async () => {
  3994. const { platform, reportTelemetryEvent } = createPlatform();
  3995. const supervisor = new ConversationTelemetrySupervisor({
  3996. platform,
  3997. workspaceScopeKey: "scope-workflow-actor",
  3998. });
  3999. spawnWorkflowActor(supervisor);
  4000. childUsage(supervisor, "wf-usage-1", "req-1");
  4001. // 同一 requestId 重放(重连 / 重放)不重复计。
  4002. childUsage(supervisor, "wf-usage-1-dup", "req-1");
  4003. supervisor.handleFact({
  4004. ...commonFact("wf-tool-start", 3, CHILD),
  4005. turnId: "child-turn-1",
  4006. kind: "tool.lifecycle",
  4007. phase: "started",
  4008. toolCallId: "bash-1",
  4009. toolName: "Bash",
  4010. });
  4011. supervisor.handleFact({
  4012. ...commonFact("wf-tool-done", 4, CHILD),
  4013. turnId: "child-turn-1",
  4014. kind: "tool.lifecycle",
  4015. phase: "completed",
  4016. toolCallId: "bash-1",
  4017. toolName: "Bash",
  4018. durationMs: 12,
  4019. });
  4020. // 一次 ask 结束:子会话自己的 turn.terminal 不是子代理终态。
  4021. supervisor.handleFact({
  4022. ...commonFact("wf-child-terminal", 5, CHILD),
  4023. turnId: "child-turn-1",
  4024. kind: "turn.terminal",
  4025. status: "success",
  4026. });
  4027. await supervisor.flushReportsForTest();
  4028. const beforeSettle = reportsByElement(reportTelemetryEvent, "agent_step");
  4029. expect(beforeSettle).toHaveLength(1);
  4030. expect(beforeSettle[0]).toEqual(
  4031. expect.objectContaining({
  4032. talkId: "parent-session",
  4033. messageId: "launch-input-1",
  4034. eventExtraDetail: expect.objectContaining({
  4035. step_type: "tool_call",
  4036. tool_name: "Bash",
  4037. tool_call_id: "tool_workflow_worker@1_bash-1",
  4038. agent_id: "worker@1",
  4039. agent_role: "workflow subagent",
  4040. workflow_run_id: "dwfrun-1",
  4041. child_session_id: CHILD,
  4042. workflow_tool_call_id: "tool-wf",
  4043. total_tokens: "0",
  4044. model_name: "glm-provider/glm-5.3",
  4045. }),
  4046. }),
  4047. );
  4048. // 第二次 ask 的用量继续累计到同一个子代理。
  4049. supervisor.handleFact({
  4050. ...commonFact("wf-usage-2", 6, CHILD),
  4051. turnId: "child-turn-2",
  4052. kind: "usage.delta",
  4053. requestId: "req-2",
  4054. providerId: "glm-provider",
  4055. modelId: "glm-5.3",
  4056. inputTokens: 200,
  4057. outputTokens: 10,
  4058. totalTokens: 210,
  4059. reasoningTokens: 0,
  4060. cacheReadTokens: 0,
  4061. cacheWriteTokens: 0,
  4062. });
  4063. settleRun(supervisor, "completed");
  4064. await supervisor.flushReportsForTest();
  4065. const steps = reportsByElement(reportTelemetryEvent, "agent_step");
  4066. expect(steps).toHaveLength(2);
  4067. expect(steps[1]).toEqual(
  4068. expect.objectContaining({
  4069. talkId: "parent-session",
  4070. messageId: "launch-input-1",
  4071. eventExtraDetail: expect.objectContaining({
  4072. step_type: "tool_call",
  4073. tool_name: "Agent",
  4074. tool_call_id: "tool_workflow_worker@1_dwfrun-1",
  4075. agent_id: "worker@1",
  4076. agent_role: "workflow subagent",
  4077. workflow_run_id: "dwfrun-1",
  4078. status: "success",
  4079. token_usage_scope: "subagent_requests",
  4080. model_request_count: "2",
  4081. input_tokens: "1200",
  4082. output_tokens: "60",
  4083. total_tokens: "1260",
  4084. model_name: "glm-provider/glm-5.3",
  4085. provider_name: "glm.example.com",
  4086. }),
  4087. }),
  4088. );
  4089. expect(reportsByElement(reportTelemetryEvent, "message_completion")).toHaveLength(0);
  4090. supervisor.dispose();
  4091. });
  4092. it("停下的 run:每个子代理一条 fail 汇总 step,错误脱敏,无 usage 时 token 为 0", async () => {
  4093. const { platform, reportTelemetryEvent } = createPlatform();
  4094. const supervisor = new ConversationTelemetrySupervisor({
  4095. platform,
  4096. workspaceScopeKey: "scope-workflow-stopped",
  4097. });
  4098. spawnWorkflowActor(supervisor);
  4099. settleRun(supervisor, "stopped", "Workflow run stopped (user)");
  4100. await supervisor.flushReportsForTest();
  4101. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toEqual([
  4102. expect.objectContaining({
  4103. messageId: "launch-input-1",
  4104. eventExtraDetail: expect.objectContaining({
  4105. tool_name: "Agent",
  4106. agent_role: "workflow subagent",
  4107. status: "fail",
  4108. error_msg: "[redacted]",
  4109. model_request_count: "0",
  4110. total_tokens: "0",
  4111. }),
  4112. }),
  4113. ]);
  4114. // 结算后迟到的用量不再改变任何上报(也不再有新的 step)。
  4115. childUsage(supervisor, "wf-late", "req-late");
  4116. await supervisor.flushReportsForTest();
  4117. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(1);
  4118. supervisor.dispose();
  4119. });
  4120. it("没有锚点(sourceCommandId 缺席)不登记也不上报", async () => {
  4121. const { platform, reportTelemetryEvent } = createPlatform();
  4122. const supervisor = new ConversationTelemetrySupervisor({
  4123. platform,
  4124. workspaceScopeKey: "scope-workflow-no-anchor",
  4125. });
  4126. supervisor.handleFact({
  4127. version: 1,
  4128. eventId: "wf-no-anchor",
  4129. eventSeq: 1,
  4130. occurredAt: 1,
  4131. sessionId: "parent-session",
  4132. kind: "workflow.lifecycle",
  4133. phase: "actor-spawned",
  4134. runId: "dwfrun-1",
  4135. agentId: "worker@1",
  4136. childSessionId: CHILD,
  4137. });
  4138. childUsage(supervisor, "wf-usage", "req-1");
  4139. settleRun(supervisor, "completed");
  4140. await supervisor.flushReportsForTest();
  4141. expect(reportsByElement(reportTelemetryEvent, "agent_step")).toHaveLength(0);
  4142. supervisor.dispose();
  4143. });
  4144. it("workflow 通知同时消费两类结果时计为 main_plus_bg_wf,来源为 background_workflow", async () => {
  4145. const { platform, reportTelemetryEvent } = createPlatform();
  4146. const supervisor = new ConversationTelemetrySupervisor({
  4147. platform,
  4148. workspaceScopeKey: "scope-workflow-composition",
  4149. });
  4150. supervisor.handleFact({
  4151. ...commonFact("wf-wake-start", 1, "session-1"),
  4152. sourceCommandId: "wf-wake-command",
  4153. kind: "turn.started",
  4154. inputSource: "background_task",
  4155. backgroundSource: "workflow",
  4156. });
  4157. supervisor.handleFact({
  4158. ...commonFact("wf-wake-terminal", 2, "session-1"),
  4159. sourceCommandId: "wf-wake-command",
  4160. kind: "turn.terminal",
  4161. status: "success",
  4162. workflowResultConsumed: true,
  4163. backgroundSubagentResultConsumed: true,
  4164. });
  4165. await supervisor.flushReportsForTest();
  4166. expect(completionAgentCompositions(reportTelemetryEvent)).toEqual(["main_plus_bg_wf"]);
  4167. expect(
  4168. reportsByElement(reportTelemetryEvent, "message_completion")[0]?.eventExtraDetail,
  4169. ).toMatchObject({ message_source: "background_workflow" });
  4170. supervisor.dispose();
  4171. });
  4172. });
  4173. describe("resolved MCP plugin usage", () => {
  4174. it("extends the existing step once and does not infer an unrelated tool", async () => {
  4175. const { platform, reportTelemetryEvent } = createPlatform();
  4176. const supervisor = new ConversationTelemetrySupervisor({
  4177. platform,
  4178. workspaceScopeKey: "mcp-plugin",
  4179. });
  4180. supervisor.acceptPromptSeed({
  4181. sessionId: "session-1",
  4182. sourceCommandId: "command-1",
  4183. memoryEnabled: true,
  4184. sendTime: 1,
  4185. extraDetail: {},
  4186. });
  4187. supervisor.handleFact({
  4188. ...commonFact("start", 1),
  4189. kind: "turn.started",
  4190. executionKind: "agent",
  4191. });
  4192. supervisor.handleFact({
  4193. ...commonFact("tool-start", 2),
  4194. kind: "tool.lifecycle",
  4195. phase: "started",
  4196. toolCallId: "call",
  4197. toolName: "mcp__demo__tool",
  4198. });
  4199. const terminal = {
  4200. ...commonFact("tool-done", 3),
  4201. kind: "tool.lifecycle" as const,
  4202. phase: "completed" as const,
  4203. toolCallId: "call",
  4204. toolName: "mcp__demo__tool",
  4205. pluginId: "demo@market",
  4206. pluginComponent: "mcp" as const,
  4207. };
  4208. supervisor.handleFact(terminal);
  4209. supervisor.handleFact(terminal);
  4210. await supervisor.flushReportsForTest();
  4211. const steps = reportsByElement(reportTelemetryEvent, "agent_step");
  4212. expect(steps).toHaveLength(1);
  4213. expect(steps[0].eventExtraDetail).toMatchObject({
  4214. plugin_id: "demo@market",
  4215. plugin_component: "mcp",
  4216. });
  4217. expect(steps[0].eventExtraDetail).not.toHaveProperty("skill_plugin_id");
  4218. supervisor.dispose();
  4219. });
  4220. });