v4ConversationTelemetrySupervisor.test.ts 140 KB

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