zcodeLegacyTaskCompatTaskIndex.test.ts 170 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400
  1. import { seedTaskIndex } from "./helpers/taskIndexFixture.js";
  2. import { readTrustedZCodeAgentV4Connection } from "#src/zcode-agent/zcodeAgentConnectionScope.js";
  3. import {
  4. readBotGroupRuntimeSnapshot,
  5. waitBotGroupExecutionEnd,
  6. } from "#src/zcode-agent/groupRuntimeSnapshot.js";
  7. import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
  8. import { tmpdir } from "node:os";
  9. import { dirname, join } from "node:path";
  10. import { afterEach, describe, expect, it, vi } from "vitest";
  11. import { Emitter, setNetworkTelemetrySink } from "@zcode/rpc";
  12. import type {
  13. SessionSummary,
  14. SessionsIndexTopicFrame,
  15. SessionsIndexTopicWireFrame,
  16. WorkspaceConfigTopicWireFrame,
  17. } from "@zcode/shared/zcode-protocol-v4";
  18. import type { NetworkObservation } from "@zcode/rpc";
  19. import {
  20. getLegacyTaskSessionSnapshotPath,
  21. getTasksIndexDatabasePath,
  22. setDataBaseDir,
  23. } from "../src/paths.js";
  24. import { createZCodeTaskServiceAdapter } from "../src/zcode-agent/zcodeTaskServiceAdapter.js";
  25. import { createZCodeTaskIndexSyncer } from "../src/zcode-agent/zcodeTaskIndexSyncer.js";
  26. import { TaskIndexRepo } from "../src/session/taskIndexRepo.js";
  27. import type { CuaProductMcpServerResolver } from "../src/cua-permission-broker/index.js";
  28. import type {
  29. IZCodeAgentService,
  30. ZCodeAgentCreateSessionParams,
  31. ZCodeAgentServiceEvent,
  32. } from "../src/zcode-agent/zcodeAgent.js";
  33. import type {
  34. AppSettings,
  35. TraceId,
  36. ZCodeMessageWithParts,
  37. ModelSelection,
  38. ZCodeProvider,
  39. ZCodeSessionEvent,
  40. ZCodeSessionStateSnapshot,
  41. ZCodeStreamEvent,
  42. ZCodeWorkspaceStateSnapshot,
  43. } from "@zcode/shared";
  44. import {
  45. resolveWorkspaceKey,
  46. ZCODE_CUA_OFFICIAL_MCP_NAMESPACE_NAME,
  47. ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  48. ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY,
  49. ZCODE_PLUGIN_ID_ENV_KEY,
  50. } from "@zcode/shared";
  51. vi.mock("#src/zcode-agent/groupRuntimeSnapshot.js", () => ({
  52. readBotGroupRuntimeSnapshot: vi.fn(async () => ({})),
  53. waitBotGroupExecutionEnd: vi.fn(async () => ({})),
  54. }));
  55. const tempDirs: string[] = [];
  56. const disposables: Array<{ disposeAll(): void }> = [];
  57. const repositories: TaskIndexRepo[] = [];
  58. const BACKGROUND_AGENT_PROVIDER_ERROR =
  59. "Requests are too frequent. Please reduce your request frequency, wait a short moment, and retry your request.";
  60. const BACKGROUND_AGENT_FAILED_SUMMARY = `Agent general-purpose task "Review" failed. ${BACKGROUND_AGENT_PROVIDER_ERROR}`;
  61. afterEach(async () => {
  62. vi.useRealTimers();
  63. setNetworkTelemetrySink(null);
  64. while (disposables.length > 0) {
  65. disposables.pop()?.disposeAll();
  66. }
  67. for (const repo of repositories.splice(0)) {
  68. await repo.ensureReady();
  69. repo.close({ throwOnError: true });
  70. }
  71. setDataBaseDir(null);
  72. while (tempDirs.length > 0) {
  73. const dir = tempDirs.pop();
  74. if (dir) {
  75. rmSync(dir, { recursive: true, force: true });
  76. }
  77. }
  78. });
  79. function useTempDataBaseDir(): string {
  80. const dir = mkdtempSync(join(tmpdir(), "zcode-task-index-"));
  81. tempDirs.push(dir);
  82. setDataBaseDir(dir);
  83. return dir;
  84. }
  85. function makeSnapshot(params: {
  86. sessionId: string;
  87. workspacePath: string;
  88. workspaceIdentity?: string;
  89. title?: string;
  90. createdAt?: number;
  91. updatedAt?: number;
  92. model?: ModelSelection;
  93. messages?: ZCodeMessageWithParts[];
  94. backgroundJobs?: ZCodeSessionStateSnapshot["projection"]["backgroundJobs"];
  95. }): ZCodeSessionStateSnapshot {
  96. const workspace = {
  97. workspacePath: params.workspacePath,
  98. workspaceIdentity: params.workspaceIdentity,
  99. workspaceKey: params.workspaceIdentity ?? params.workspacePath,
  100. };
  101. const model = params.model ?? { providerId: "glm", modelId: "glm-4.6" };
  102. return {
  103. protocol: { name: "ZCode Protocol", version: 1 },
  104. session: {
  105. sessionId: params.sessionId,
  106. workspace,
  107. sessionKind: "interactive",
  108. title: params.title ?? "Indexed session",
  109. mode: "build",
  110. status: "idle",
  111. model,
  112. createdAt: params.createdAt ?? 10,
  113. updatedAt: params.updatedAt ?? 20,
  114. },
  115. settings: {
  116. model: {
  117. current: model,
  118. available: [
  119. {
  120. ref: model,
  121. label: model.modelId,
  122. contextWindow: 128000,
  123. },
  124. ],
  125. lastUsed: model,
  126. },
  127. thoughtLevel: {
  128. enabled: true,
  129. current: "think",
  130. available: [{ value: "think", label: "Think" }],
  131. },
  132. mode: { current: "build" },
  133. },
  134. projection: {
  135. sessionId: params.sessionId,
  136. status: "idle",
  137. mode: "build",
  138. turnCount: 0,
  139. totalTokenCount: 0,
  140. contextUsed: 0,
  141. contextWindow: 128000,
  142. pendingPermissions: [],
  143. activeToolCalls: [],
  144. backgroundJobs: params.backgroundJobs ?? [],
  145. },
  146. runtime: { eventSeq: 0, stateRevision: 1, pendingRequestIds: [] },
  147. messages: params.messages ?? [],
  148. };
  149. }
  150. function makeUserMessage(params: {
  151. sessionId: string;
  152. messageId: string;
  153. parts?: ZCodeMessageWithParts["parts"];
  154. text: string;
  155. }): ZCodeMessageWithParts {
  156. return {
  157. info: {
  158. messageId: params.messageId,
  159. sessionId: params.sessionId,
  160. role: "user",
  161. time: { created: 30 },
  162. agent: "glm",
  163. model: { providerId: "glm", modelId: "glm-4.6" },
  164. },
  165. parts: params.parts ?? [
  166. {
  167. partId: `${params.messageId}_part_1`,
  168. sessionId: params.sessionId,
  169. messageId: params.messageId,
  170. type: "text",
  171. text: params.text,
  172. },
  173. ],
  174. };
  175. }
  176. function makeAssistantAgentToolMessage(params: {
  177. sessionId: string;
  178. messageId: string;
  179. toolCallId: string;
  180. }): ZCodeMessageWithParts {
  181. return {
  182. info: {
  183. messageId: params.messageId,
  184. sessionId: params.sessionId,
  185. role: "assistant",
  186. time: { created: 40, completed: 50 },
  187. agent: "glm",
  188. model: { providerId: "glm", modelId: "glm-4.6" },
  189. },
  190. parts: [
  191. {
  192. partId: `${params.messageId}_tool_1`,
  193. sessionId: params.sessionId,
  194. messageId: params.messageId,
  195. type: "tool",
  196. callId: params.toolCallId,
  197. tool: "Agent",
  198. state: {
  199. status: "completed",
  200. input: { prompt: "Explore project structure" },
  201. output: "Explore summary",
  202. title: "Agent",
  203. metadata: {},
  204. startedAt: 41,
  205. completedAt: 49,
  206. },
  207. },
  208. ],
  209. };
  210. }
  211. function createAgentMock() {
  212. const eventEmitter = new Emitter<ZCodeAgentServiceEvent>();
  213. const indexFrameEmitter = new Emitter<SessionsIndexTopicWireFrame>();
  214. const snapshots = new Map<string, ZCodeSessionStateSnapshot>();
  215. const workspaceState = (params: {
  216. workspacePath: string;
  217. workspaceIdentity?: string;
  218. }): ZCodeWorkspaceStateSnapshot => {
  219. const snapshot =
  220. [...snapshots.values()].find(
  221. (item) =>
  222. item.session.workspace.workspacePath === params.workspacePath &&
  223. item.session.workspace.workspaceIdentity === params.workspaceIdentity,
  224. ) ??
  225. makeSnapshot({
  226. sessionId: "draft",
  227. workspacePath: params.workspacePath,
  228. workspaceIdentity: params.workspaceIdentity,
  229. });
  230. return {
  231. workspace: snapshot.session.workspace,
  232. settings: snapshot.settings,
  233. };
  234. };
  235. const agent: IZCodeAgentService = {
  236. reconcileSessionsIndexV4: vi.fn(async ({ sessionIds }) => ({
  237. sessions: sessionIds.map((sessionId) => {
  238. const snapshot = snapshots.get(sessionId);
  239. // 夹具模拟 CLI 持久会话;结果固定为已完成,不从运行态反推持久结果。
  240. return snapshot
  241. ? {
  242. sessionId,
  243. exists: true as const,
  244. deleted: false,
  245. title: snapshot.session.title,
  246. titleSource: "generated",
  247. createdAt: snapshot.session.createdAt,
  248. updatedAt: snapshot.session.updatedAt,
  249. lastOutcome: "completed" as const,
  250. }
  251. : { sessionId, exists: false as const, deleted: false };
  252. }),
  253. })),
  254. initialize: vi.fn(async (params) => ({
  255. available: true,
  256. workspaceKey: params.workspaceIdentity ?? params.workspacePath,
  257. protocolName: "ZCode Protocol",
  258. protocolVersion: 1,
  259. transportKind: "stdio",
  260. })),
  261. createSession: vi.fn(async (params: ZCodeAgentCreateSessionParams) => {
  262. const sessionId = params.sessionId ?? `sess_${snapshots.size + 1}`;
  263. const snapshot = makeSnapshot({
  264. sessionId,
  265. workspacePath: params.workspacePath,
  266. workspaceIdentity: params.workspaceIdentity,
  267. model: params.model,
  268. title: params.importedHistory?.title,
  269. createdAt: params.importedHistory?.createdAt,
  270. updatedAt: params.importedHistory?.updatedAt,
  271. messages: params.importedHistory?.messages.map((message, index) =>
  272. message.role === "assistant"
  273. ? ({
  274. info: {
  275. messageId: `msg_import_${index}`,
  276. sessionId,
  277. role: "assistant",
  278. time: {
  279. created: message.timestamp ?? 30 + index,
  280. completed: message.timestamp ?? 30 + index,
  281. },
  282. parentMessageId: `msg_import_${Math.max(0, index - 1)}`,
  283. agent: "glm",
  284. model: { providerId: "glm", modelId: "glm-4.6" },
  285. path: {
  286. cwd: params.workspacePath,
  287. root: params.workspacePath,
  288. },
  289. cost: 0,
  290. tokens: {
  291. input: 0,
  292. output: 0,
  293. reasoning: 0,
  294. cache: { read: 0, write: 0 },
  295. },
  296. },
  297. parts: [
  298. {
  299. partId: `part_import_${index}`,
  300. sessionId,
  301. messageId: `msg_import_${index}`,
  302. type: "text",
  303. text: message.content,
  304. },
  305. ],
  306. } satisfies ZCodeMessageWithParts)
  307. : makeUserMessage({
  308. sessionId,
  309. messageId: `msg_import_${index}`,
  310. text: message.content,
  311. }),
  312. ),
  313. });
  314. snapshots.set(snapshot.session.sessionId, snapshot);
  315. return snapshot;
  316. }),
  317. resumeSession: vi.fn(async (params) => {
  318. const snapshot = snapshots.get(params.sessionId);
  319. if (!snapshot) {
  320. throw new Error(`Session not found: ${params.sessionId}`);
  321. }
  322. return snapshot;
  323. }),
  324. listSessions: vi.fn(async () => {
  325. throw new Error("listSessions should not be used for task index lists");
  326. }),
  327. getTaskTokenUsage: vi.fn(async (params) => ({
  328. sessionId: params.sessionId,
  329. totalTokens: 0,
  330. inputTokens: 0,
  331. outputTokens: 0,
  332. reasoningTokens: 0,
  333. cacheCreationTokens: 0,
  334. cacheReadTokens: 0,
  335. modelRequestCount: 0,
  336. modelErrorCount: 0,
  337. inputBaselineBySource: {},
  338. })),
  339. readSession: vi.fn(
  340. async (params) =>
  341. snapshots.get(params.sessionId) ??
  342. makeSnapshot({
  343. sessionId: params.sessionId,
  344. workspacePath: params.workspacePath,
  345. workspaceIdentity: params.workspaceIdentity,
  346. }),
  347. ),
  348. readSessionMessages: vi.fn(async () => []),
  349. readSessionEvents: vi.fn(async () => []),
  350. readWorkspacePresentation: vi.fn(async (params) => ({
  351. workspace: workspaceState(params).workspace,
  352. mode: "build" as const,
  353. slashCommands: [],
  354. })),
  355. sendPrompt: vi.fn(
  356. async (params) =>
  357. snapshots.get(params.sessionId) ??
  358. makeSnapshot({
  359. sessionId: params.sessionId,
  360. workspacePath: params.workspacePath,
  361. workspaceIdentity: params.workspaceIdentity,
  362. }),
  363. ),
  364. // M5 ③-2:send/stop/交互回执主路径收敛 v4 命令面(旧 sendPrompt 仅剩附件回退分支)。
  365. sendConversationCommandV4: vi.fn(async (params) => ({
  366. commandId: params.envelope.commandId,
  367. status: "accepted" as const,
  368. revisionAtDecision: 1,
  369. ...(params.envelope.type === "createSession"
  370. ? {
  371. result: {
  372. type: "createSession" as const,
  373. sessionId: "sess_v4_created",
  374. },
  375. }
  376. : {}),
  377. })),
  378. closeSession: vi.fn(async () => undefined),
  379. upsertModelProvider: vi.fn(async (params) => workspaceState(params)),
  380. removeModelProvider: vi.fn(async (params) => workspaceState(params)),
  381. setModel: vi.fn(
  382. async (params) =>
  383. snapshots.get(params.sessionId) ??
  384. makeSnapshot({
  385. sessionId: params.sessionId,
  386. workspacePath: params.workspacePath,
  387. workspaceIdentity: params.workspaceIdentity,
  388. }),
  389. ),
  390. setThoughtLevel: vi.fn(
  391. async (params) =>
  392. snapshots.get(params.sessionId) ??
  393. makeSnapshot({
  394. sessionId: params.sessionId,
  395. workspacePath: params.workspacePath,
  396. workspaceIdentity: params.workspaceIdentity,
  397. }),
  398. ),
  399. setMode: vi.fn(
  400. async (params) =>
  401. snapshots.get(params.sessionId) ??
  402. makeSnapshot({
  403. sessionId: params.sessionId,
  404. workspacePath: params.workspacePath,
  405. workspaceIdentity: params.workspaceIdentity,
  406. }),
  407. ),
  408. onDynamicSessionEvent: vi.fn(() => eventEmitter.event),
  409. // M5 删波次 2:syncer 的终态/ready 摄入换到 v4 sessions-index 帧,
  410. // 真实 syncer 会在首个 session 激活信号时建立 workspace 级订阅。
  411. subscribeSessionsIndexV4: vi.fn(async () => {
  412. // fresh subscribe 必须先给 syncer 一份完整 initial snapshot;后续 ready deltas
  413. // 才能在同一 log epoch/seq 链上作为权威状态迁移被消费。
  414. fireIndexSnapshot(indexFrameEmitter);
  415. return {
  416. ack: {
  417. subscriptionId: "six-compat-1",
  418. mode: "snapshot" as const,
  419. logEpoch: "epoch-compat",
  420. },
  421. };
  422. }),
  423. unsubscribeSessionsIndexV4: vi.fn(async () => undefined),
  424. onDynamicSessionsIndexFrame: vi.fn(() => indexFrameEmitter.event),
  425. subscribeWorkspaceConfigV4: vi.fn(async () => ({
  426. ack: {
  427. subscriptionId: "wcs-compat-1",
  428. mode: "snapshot" as const,
  429. logEpoch: "epoch-compat-cfg",
  430. },
  431. })),
  432. unsubscribeWorkspaceConfigV4: vi.fn(async () => undefined),
  433. onDynamicWorkspaceConfigFrame: vi.fn(() => new Emitter<WorkspaceConfigTopicWireFrame>().event),
  434. hasActiveCuaOperationTurn: vi.fn(() => false),
  435. disposeWorkspace: vi.fn(async () => undefined),
  436. disposeAll: vi.fn(),
  437. };
  438. return { agent, eventEmitter, indexFrameEmitter };
  439. }
  440. function createService(options?: {
  441. settings?: Partial<AppSettings>;
  442. cuaProductMcpServerResolver?: CuaProductMcpServerResolver;
  443. }) {
  444. useTempDataBaseDir();
  445. const { agent, eventEmitter, indexFrameEmitter } = createAgentMock();
  446. const settingService = options?.settings
  447. ? {
  448. get: vi.fn(
  449. async () =>
  450. ({
  451. recentProjects: [],
  452. locale: "zh-CN",
  453. ...options.settings,
  454. }) as AppSettings,
  455. ),
  456. }
  457. : undefined;
  458. // adapter 现在要求注入 syncer;测试里给一个真实的 syncer(agent 上面已经 mock 了 onDynamicSessionEvent)。
  459. // 旧夹具跟随全局路径,迟到的异步初始化会打开下一用例的库并造成锁冲突。
  460. // 与真实 Host 装配一样固定数据库路径,并在删除夹具目录前关闭连接。
  461. const taskIndexRepo = new TaskIndexRepo(undefined, undefined, getTasksIndexDatabasePath());
  462. repositories.push(taskIndexRepo);
  463. const taskIndexSyncer = createZCodeTaskIndexSyncer({
  464. agentService: agent,
  465. taskIndexRepo,
  466. });
  467. const service = createZCodeTaskServiceAdapter({
  468. zcodeAgentService: agent,
  469. taskIndexRepo,
  470. taskIndexSyncer,
  471. ...(settingService ? { settingService } : {}),
  472. ...(options?.cuaProductMcpServerResolver
  473. ? { cuaProductMcpServerResolver: options.cuaProductMcpServerResolver }
  474. : {}),
  475. }) as ReturnType<typeof createZCodeTaskServiceAdapter> & {
  476. disposeAll(): void;
  477. };
  478. disposables.push(service);
  479. return { agent, eventEmitter, indexFrameEmitter, service, taskIndexRepo };
  480. }
  481. async function flushMicrotasks(times = 5): Promise<void> {
  482. for (let index = 0; index < times; index += 1) {
  483. await Promise.resolve();
  484. }
  485. }
  486. const compatIndexFrameSeqByEmitter = new WeakMap<Emitter<SessionsIndexTopicWireFrame>, number>();
  487. function fireIndexSnapshot(indexFrameEmitter: Emitter<SessionsIndexTopicWireFrame>): void {
  488. const seq = 100;
  489. compatIndexFrameSeqByEmitter.set(indexFrameEmitter, seq);
  490. const frame: SessionsIndexTopicFrame = {
  491. topic: "sessions-index//repo",
  492. subscriptionId: "six-compat-1",
  493. fromSeq: 0,
  494. toSeq: seq,
  495. sentAt: 100,
  496. payload: {
  497. kind: "snapshot",
  498. snapshot: {
  499. protocolVersion: 1,
  500. workspaceId: "/repo",
  501. logEpoch: "epoch-compat",
  502. sessions: [],
  503. },
  504. },
  505. };
  506. indexFrameEmitter.fire({
  507. wireVersion: 3,
  508. deliveryKind: "online",
  509. kind: "complete",
  510. logicalFrameId: `logical-compat-${seq}`,
  511. logicalFrameOrdinal: seq,
  512. topic: frame.topic,
  513. subscriptionId: frame.subscriptionId,
  514. frame,
  515. });
  516. }
  517. function compatSummary(
  518. sessionId: string,
  519. phase: "running" | "completedSuccess" | "error",
  520. ): SessionSummary {
  521. return {
  522. sessionId,
  523. workspaceId: "/repo",
  524. title: "",
  525. phase,
  526. sessionEnded: phase !== "running",
  527. hasBackgroundWork: false,
  528. lastActivityAt: 100,
  529. createdAt: 1,
  530. };
  531. }
  532. function fireIndexUpsert(
  533. indexFrameEmitter: Emitter<SessionsIndexTopicWireFrame>,
  534. session: SessionSummary,
  535. ): void {
  536. const compatIndexFrameSeq = (compatIndexFrameSeqByEmitter.get(indexFrameEmitter) ?? 0) + 1;
  537. compatIndexFrameSeqByEmitter.set(indexFrameEmitter, compatIndexFrameSeq);
  538. const frame: SessionsIndexTopicFrame = {
  539. topic: "sessions-index//repo",
  540. subscriptionId: "six-compat-1",
  541. fromSeq: compatIndexFrameSeq - 1,
  542. toSeq: compatIndexFrameSeq,
  543. sentAt: 100,
  544. payload: { kind: "deltas", deltas: [{ op: "session.upserted", session }] },
  545. };
  546. indexFrameEmitter.fire({
  547. wireVersion: 3,
  548. deliveryKind: "online",
  549. kind: "complete",
  550. logicalFrameId: `logical-compat-${compatIndexFrameSeq}`,
  551. logicalFrameOrdinal: compatIndexFrameSeq,
  552. topic: frame.topic,
  553. subscriptionId: frame.subscriptionId,
  554. frame,
  555. });
  556. }
  557. /**
  558. * M5 删波次 2:prompt ready 边界改由 v4 sessions-index 的 phase 终态迁移驱动
  559. * (running → completedSuccess),替代旧 state.updated prompt_completed 通知。
  560. */
  561. async function firePromptCompletedState(
  562. indexFrameEmitter: Emitter<SessionsIndexTopicWireFrame>,
  563. params: {
  564. sessionId: string;
  565. workspacePath: string;
  566. workspaceIdentity?: string;
  567. },
  568. ): Promise<void> {
  569. // 等 syncer 的 workspace v4 订阅建立完(subscriptionId 闸门就位)。
  570. await flushMicrotasks();
  571. fireIndexUpsert(indexFrameEmitter, compatSummary(params.sessionId, "running"));
  572. fireIndexUpsert(indexFrameEmitter, compatSummary(params.sessionId, "completedSuccess"));
  573. }
  574. async function seedIndexedTask(
  575. repo: TaskIndexRepo,
  576. params: {
  577. taskId: string;
  578. provider: ZCodeProvider;
  579. model?: string;
  580. workspacePath?: string;
  581. createdAt?: number;
  582. updatedAt?: number;
  583. pinned?: boolean;
  584. archived?: boolean;
  585. migrationSource?: "claudeCode";
  586. thoughtLevel?: string;
  587. },
  588. ) {
  589. await seedTaskIndex(repo, {
  590. meta: {
  591. taskId: params.taskId,
  592. traceId: `trace_${params.taskId}`,
  593. title: params.taskId,
  594. workspacePath: params.workspacePath ?? "/repo",
  595. createdAt: params.createdAt ?? 10,
  596. updatedAt: params.updatedAt ?? 20,
  597. mode: "build",
  598. status: "completed",
  599. provider: params.provider,
  600. ...(params.model ? { model: params.model } : {}),
  601. ...(params.thoughtLevel ? { thoughtLevel: params.thoughtLevel } : {}),
  602. ...(params.migrationSource ? { migrationSource: params.migrationSource } : {}),
  603. },
  604. pinned: params.pinned,
  605. archived: params.archived,
  606. });
  607. }
  608. async function seedLegacyAcpSessionId(
  609. repo: TaskIndexRepo,
  610. params: {
  611. workspacePath: string;
  612. workspaceIdentity?: string;
  613. taskId: string;
  614. acpSessionId: string;
  615. },
  616. ) {
  617. await repo.ensureReady();
  618. const db = (
  619. repo as unknown as {
  620. getDatabase(): {
  621. exec(sql: string): unknown;
  622. prepare(sql: string): {
  623. run(...args: unknown[]): unknown;
  624. };
  625. };
  626. }
  627. ).getDatabase();
  628. db.exec("ALTER TABLE tasks ADD COLUMN acp_session_id TEXT");
  629. db.prepare(`UPDATE tasks SET acp_session_id = ? WHERE workspace_key = ? AND task_id = ?`).run(
  630. params.acpSessionId,
  631. resolveWorkspaceKey(params),
  632. params.taskId,
  633. );
  634. // Bugfix: 老库的 acp_session_id 只在初始化迁移阶段读取。
  635. // 测试里手工补列后重开 repo,验证迁移不是运行时 facade 兜底。
  636. repo.close();
  637. await repo.ensureReady();
  638. }
  639. describe("ZCode legacy task compat task index", () => {
  640. it("各夹具的迟到写入保持在自己的数据库中", async () => {
  641. const first = createService();
  642. await first.taskIndexRepo.ensureReady();
  643. const second = createService();
  644. await second.taskIndexRepo.ensureReady();
  645. await seedIndexedTask(first.taskIndexRepo, { taskId: "late-first", provider: "zcode" });
  646. expect(await second.taskIndexRepo.listReconciliationRows({ workspacePath: "/repo" })).toEqual(
  647. [],
  648. );
  649. expect(await first.taskIndexRepo.listReconciliationRows({ workspacePath: "/repo" })).toEqual([
  650. expect.objectContaining({ meta: expect.objectContaining({ taskId: "late-first" }) }),
  651. ]);
  652. });
  653. it("creates fresh CLI identities for explicit imports instead of overwriting a deleted import", async () => {
  654. const { service, taskIndexRepo } = createService();
  655. const module = await import("../src/session/claude-native/claudeNativeSessionImportService.js");
  656. const spy = vi
  657. .spyOn(module, "importClaudeNativeSessions")
  658. .mockImplementation(async (params) => {
  659. const source = {
  660. provider: "claude" as const,
  661. workspacePath: "/repo",
  662. sessionId: "external",
  663. sourcePath: "/fixture.jsonl",
  664. title: "Imported",
  665. createdAt: 1,
  666. updatedAt: 2,
  667. messages: [{ role: "user" as const, content: "hello", timestamp: 1 }],
  668. };
  669. const first = await params.createImportedSession(source);
  670. await taskIndexRepo.applyCliDeletion({ workspacePath: "/repo", taskId: first.taskId });
  671. const second = await params.createImportedSession(source);
  672. expect(second.taskId).not.toBe(first.taskId);
  673. expect(await taskIndexRepo.getTaskMeta(first)).toBeNull();
  674. return { imported: [], failed: [], skipped: [] };
  675. });
  676. try {
  677. await service.importClaudeSessions({ workspacePath: "/repo", sessionIds: ["external"] });
  678. } finally {
  679. spy.mockRestore();
  680. }
  681. });
  682. it.each([undefined, "ssh://host/repo"])(
  683. "waits for an in-flight topic admission before confirming cancellation (%s)",
  684. async (workspaceIdentity) => {
  685. const { service, agent } = createService();
  686. const task = await service.createTask({
  687. workspacePath: "/repo",
  688. workspaceIdentity,
  689. provider: "glm",
  690. });
  691. const target = { taskId: task.taskId, workspacePath: "/repo", workspaceIdentity };
  692. let release!: () => void;
  693. agent.sendConversationCommandV4 = vi.fn(async () => {
  694. await new Promise<void>((resolve) => {
  695. release = resolve;
  696. });
  697. return { commandId: "topic-inflight", status: "accepted", revisionAtDecision: 1 };
  698. });
  699. const sending = service.submitBotGroupInput!({
  700. ...target,
  701. commandId: "topic-inflight",
  702. content: "read",
  703. source: {
  704. provider: "feishu",
  705. botId: "bot",
  706. chatId: "chat",
  707. threadId: "topic",
  708. messageId: "message",
  709. senderId: "owner",
  710. senderName: "Owner",
  711. },
  712. });
  713. await vi.waitFor(() => expect(release).toBeTypeOf("function"));
  714. let cancelled = false;
  715. const cancellation = service.invalidateBotTopicInputs!(target).then(() => {
  716. cancelled = true;
  717. });
  718. await flushMicrotasks();
  719. const completedBeforeAdmission = cancelled;
  720. // 总是释放挂起请求,失败断言也不能遗留正在写入临时任务的异步工作。
  721. release();
  722. await Promise.all([sending, cancellation]);
  723. expect(completedBeforeAdmission).toBe(false);
  724. expect(cancelled).toBe(true);
  725. },
  726. );
  727. it("does not admit an uploaded topic input after cancellation", async () => {
  728. const { service, agent } = createService();
  729. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  730. let finish!: () => void;
  731. agent.attachmentBeginV4 = vi.fn(async (p) => ({
  732. uploadId: p.uploadId,
  733. state: "staging" as const,
  734. nextChunkIndex: 0,
  735. }));
  736. agent.attachmentChunkV4 = vi.fn(async (p) => ({ uploadId: p.uploadId, nextChunkIndex: 1 }));
  737. agent.attachmentCommitV4 = vi.fn(async (p) => {
  738. await new Promise<void>((resolve) => {
  739. finish = resolve;
  740. });
  741. return { uploadId: p.uploadId, ref: "artifact://prepared" };
  742. });
  743. const sending = service.submitBotGroupInput!({
  744. taskId: task.taskId,
  745. workspacePath: "/repo",
  746. commandId: "topic-upload",
  747. content: "read",
  748. attachments: [
  749. { kind: "file", filename: "input.txt", textContent: "material", mimeType: "text/plain" },
  750. ],
  751. source: {
  752. provider: "feishu",
  753. botId: "bot",
  754. chatId: "chat",
  755. threadId: "topic",
  756. messageId: "message",
  757. senderId: "owner",
  758. senderName: "Owner",
  759. },
  760. });
  761. await vi.waitFor(() => expect(finish).toBeTypeOf("function"));
  762. await service.invalidateBotTopicInputs!({ taskId: task.taskId, workspacePath: "/repo" });
  763. finish();
  764. await expect(sending).rejects.toThrow(/cancelled/);
  765. expect(agent.sendConversationCommandV4).not.toHaveBeenCalled();
  766. });
  767. it("uploads Bot attachments and admits input on the same trusted connection", async () => {
  768. const { service, agent } = createService();
  769. const task = await service.createTask({
  770. workspacePath: "/repo",
  771. workspaceIdentity: "ssh://host/repo",
  772. provider: "glm",
  773. });
  774. const connections: string[] = [];
  775. const check = (params: unknown) => {
  776. const connection = readTrustedZCodeAgentV4Connection(params);
  777. if (!connection) throw new Error("fault.attachment.connectionUntrusted");
  778. expect(connection.clientMode).toBe("desktop-continuous");
  779. expect(params).toEqual(
  780. expect.objectContaining({
  781. workspaceIdentity: "ssh://host/repo",
  782. remoteSessionId: "current-remote",
  783. }),
  784. );
  785. connections.push(connection.connectionId);
  786. };
  787. agent.attachmentBeginV4 = vi.fn(async (params) => {
  788. check(params);
  789. return { uploadId: params.uploadId, state: "staging" as const, nextChunkIndex: 0 };
  790. });
  791. agent.attachmentChunkV4 = vi.fn(async (params) => {
  792. check(params);
  793. return { uploadId: params.uploadId, nextChunkIndex: 1 };
  794. });
  795. agent.attachmentCommitV4 = vi.fn(async (params) => {
  796. check(params);
  797. return { uploadId: params.uploadId, ref: "artifact://bot-file" };
  798. });
  799. agent.attachmentAbortV4 = vi.fn(async () => undefined);
  800. agent.sendConversationCommandV4 = vi.fn(async (params) => {
  801. check(params);
  802. expect(params.envelope.payload).toEqual(
  803. expect.objectContaining({
  804. attachments: [expect.objectContaining({ ref: "artifact://bot-file" })],
  805. }),
  806. );
  807. return {
  808. commandId: params.envelope.commandId,
  809. status: "accepted" as const,
  810. revisionAtDecision: 1,
  811. result: {
  812. type: "inputAccepted" as const,
  813. inputId: params.envelope.commandId,
  814. delivery: "queue" as const,
  815. },
  816. };
  817. });
  818. await service.submitBotGroupInput!({
  819. taskId: task.taskId,
  820. workspacePath: "/repo",
  821. workspaceIdentity: "ssh://host/repo",
  822. remoteSessionId: "current-remote",
  823. commandId: "group-with-file",
  824. content: "Read this file",
  825. attachments: [
  826. { kind: "file", filename: "example.txt", mimeType: "text/plain", textContent: "hello" },
  827. ],
  828. source: {
  829. provider: "feishu",
  830. botId: "bot",
  831. chatId: "chat",
  832. senderId: "member",
  833. messageId: "message",
  834. },
  835. });
  836. expect(connections).toHaveLength(4);
  837. expect(new Set(connections).size).toBe(1);
  838. });
  839. it("keeps trusted remote session routing on group admission and rejects a foreign workspace before IO", async () => {
  840. const { service, agent } = createService();
  841. const task = await service.createTask({
  842. workspacePath: "/repo",
  843. workspaceIdentity: "ssh://host/repo",
  844. provider: "glm",
  845. });
  846. agent.sendConversationCommandV4 = vi.fn(async (params) => ({
  847. commandId: params.envelope.commandId,
  848. status: "accepted" as const,
  849. revisionAtDecision: 1,
  850. result: {
  851. type: "inputAccepted" as const,
  852. inputId: params.envelope.commandId,
  853. delivery: "queue" as const,
  854. },
  855. }));
  856. const input = {
  857. taskId: task.taskId,
  858. workspacePath: "/repo",
  859. workspaceIdentity: "ssh://host/repo",
  860. remoteSessionId: "current-remote",
  861. commandId: "group-command",
  862. content: "hello",
  863. source: {
  864. provider: "feishu" as const,
  865. botId: "bot",
  866. chatId: "group",
  867. senderId: "member",
  868. senderName: "Member",
  869. messageId: "message",
  870. threadId: "omt_source",
  871. rootMessageId: "om_root",
  872. },
  873. };
  874. vi.mocked(readBotGroupRuntimeSnapshot).mockClear();
  875. vi.mocked(agent.sendConversationCommandV4).mockImplementation(async (params) => {
  876. // 冷启动时先恢复同一任务,不能依赖 Desktop 曾经打开过它。
  877. expect(readBotGroupRuntimeSnapshot).toHaveBeenCalledWith(expect.any(Object), {
  878. workspacePath: "/repo",
  879. workspaceIdentity: "ssh://host/repo",
  880. remoteSessionId: "current-remote",
  881. sessionId: task.taskId,
  882. });
  883. return {
  884. commandId: params.envelope.commandId,
  885. status: "accepted",
  886. revisionAtDecision: 1,
  887. result: { type: "inputAccepted", inputId: params.envelope.commandId, delivery: "queue" },
  888. };
  889. });
  890. await service.submitBotGroupInput!(input);
  891. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith(
  892. expect.objectContaining({
  893. workspaceIdentity: "ssh://host/repo",
  894. remoteSessionId: "current-remote",
  895. envelope: expect.objectContaining({
  896. payload: expect.objectContaining({
  897. requestedDelivery: "startNow",
  898. botDeliveryTarget: expect.objectContaining({
  899. threadId: "omt_source",
  900. rootMessageId: "om_root",
  901. }),
  902. }),
  903. }),
  904. }),
  905. );
  906. await expect(
  907. service.submitBotGroupInput!({ ...input, workspaceIdentity: "ssh://other/repo" }),
  908. ).rejects.toThrow("workspace mismatch");
  909. await expect(
  910. service.getBotGroupTaskBlockReason!({
  911. taskId: task.taskId,
  912. workspacePath: "/repo",
  913. workspaceIdentity: "ssh://other/repo",
  914. }),
  915. ).rejects.toThrow("workspace mismatch");
  916. expect(agent.sendConversationCommandV4).toHaveBeenCalledOnce();
  917. vi.mocked(readBotGroupRuntimeSnapshot).mockRejectedValueOnce(new Error("restore failed"));
  918. await expect(
  919. service.submitBotGroupInput!({ ...input, commandId: "cold-failure" }),
  920. ).rejects.toThrow("restore failed");
  921. expect(agent.sendConversationCommandV4).toHaveBeenCalledOnce();
  922. await service.readBotTopicSummaries!({
  923. taskId: task.taskId,
  924. workspacePath: "/repo",
  925. workspaceIdentity: "ssh://host/repo",
  926. remoteSessionId: "current-remote",
  927. });
  928. expect(agent.readSessionMessages).toHaveBeenCalledWith(
  929. expect.objectContaining({
  930. sessionId: task.taskId,
  931. workspaceIdentity: "ssh://host/repo",
  932. remoteSessionId: "current-remote",
  933. }),
  934. );
  935. await expect(
  936. service.readBotTopicSummaries!({
  937. taskId: task.taskId,
  938. workspacePath: "/repo",
  939. workspaceIdentity: "ssh://other/repo",
  940. }),
  941. ).rejects.toThrow("workspace mismatch");
  942. });
  943. it("exposes task ready only after the indexed session returns to an input-ready phase", async () => {
  944. const { indexFrameEmitter, service } = createService();
  945. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  946. const readyReasons: string[] = [];
  947. const disposable = service.onDynamicTaskReady(task.taskId)((event) => {
  948. readyReasons.push(event.reason);
  949. });
  950. try {
  951. await flushMicrotasks();
  952. fireIndexUpsert(indexFrameEmitter, compatSummary("another-task", "running"));
  953. fireIndexUpsert(indexFrameEmitter, compatSummary("another-task", "completedSuccess"));
  954. fireIndexUpsert(indexFrameEmitter, compatSummary(task.taskId, "running"));
  955. fireIndexUpsert(indexFrameEmitter, compatSummary(task.taskId, "completedSuccess"));
  956. fireIndexUpsert(indexFrameEmitter, compatSummary(task.taskId, "running"));
  957. fireIndexUpsert(indexFrameEmitter, compatSummary(task.taskId, "error"));
  958. await flushMicrotasks();
  959. expect(readyReasons).toEqual(["prompt_completed", "prompt_failed"]);
  960. } finally {
  961. disposable.dispose();
  962. }
  963. });
  964. it("reports the manual automation runId on terminal outcome", async () => {
  965. const { indexFrameEmitter, service } = createService();
  966. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  967. const outcomes: Array<{ inputId?: string; outcome: string }> = [];
  968. const disposable = service.onDynamicTaskTerminalOutcome(task.taskId)((event) => {
  969. outcomes.push(event);
  970. });
  971. const runId = "automation-1:manual:1700000000000";
  972. try {
  973. await service.sendPrompt({
  974. taskId: task.taskId,
  975. traceId: runId,
  976. content: "run scheduled report",
  977. automationId: "automation-1",
  978. });
  979. await flushMicrotasks();
  980. fireIndexUpsert(indexFrameEmitter, compatSummary(task.taskId, "running"));
  981. fireIndexUpsert(indexFrameEmitter, compatSummary(task.taskId, "completedSuccess"));
  982. await flushMicrotasks();
  983. expect(outcomes).toEqual([expect.objectContaining({ inputId: runId, outcome: "succeeded" })]);
  984. } finally {
  985. disposable.dispose();
  986. }
  987. });
  988. it("keeps automation mutation isolation turn-scoped when creating an execution task", async () => {
  989. const { agent, service, taskIndexRepo } = createService();
  990. const task = await service.createTask({
  991. workspacePath: "/repo",
  992. provider: "glm",
  993. automationId: "automation-1",
  994. });
  995. const createParams = vi.mocked(agent.createSession).mock.calls[0]?.[0];
  996. expect(createParams).toEqual(
  997. expect.objectContaining({
  998. workspacePath: "/repo",
  999. persistence: "deferred",
  1000. titleGenerationEnabled: false,
  1001. }),
  1002. );
  1003. expect(createParams).not.toHaveProperty("toolDenylist");
  1004. await expect(
  1005. taskIndexRepo.getTaskMeta({
  1006. workspacePath: "/repo",
  1007. taskId: task.taskId,
  1008. }),
  1009. ).resolves.toEqual(expect.objectContaining({ cronAutomationId: "automation-1" }));
  1010. });
  1011. it("preserves an explicitly empty frozen directory list across adapter create and resume", async () => {
  1012. const { agent, service } = createService();
  1013. await service.createTask({
  1014. workspacePath: "/repo",
  1015. projectId: "p",
  1016. additionalDirectories: [],
  1017. v4Create: true,
  1018. });
  1019. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith(
  1020. expect.objectContaining({
  1021. projectId: "p",
  1022. envelope: expect.objectContaining({
  1023. payload: expect.objectContaining({ additionalDirectories: [] }),
  1024. }),
  1025. }),
  1026. );
  1027. const nativeTask = await service.createTask({
  1028. workspacePath: "/repo",
  1029. projectId: "p",
  1030. additionalDirectories: [],
  1031. });
  1032. expect(agent.createSession).toHaveBeenCalledWith(
  1033. expect.objectContaining({ projectId: "p", additionalDirectories: [] }),
  1034. );
  1035. await service.resumeTask({
  1036. workspacePath: "/repo",
  1037. taskId: nativeTask.taskId,
  1038. additionalDirectories: [],
  1039. });
  1040. expect(agent.resumeSession).toHaveBeenCalledWith(
  1041. expect.objectContaining({ additionalDirectories: [] }),
  1042. );
  1043. });
  1044. it("SAT28: 显式恢复 child 只返回详情,不创建主列表索引", async () => {
  1045. const { agent, service, taskIndexRepo } = createService();
  1046. const snapshot = makeSnapshot({ sessionId: "hidden-child", workspacePath: "/repo" });
  1047. snapshot.session.sessionKind = "subagent_child";
  1048. vi.mocked(agent.resumeSession).mockResolvedValue(snapshot);
  1049. await service.resumeTask({ workspacePath: "/repo", taskId: "hidden-child" });
  1050. expect(
  1051. await taskIndexRepo.getTaskMeta({ workspacePath: "/repo", taskId: "hidden-child" }),
  1052. ).toBeNull();
  1053. });
  1054. it("keeps automation mutation isolation turn-scoped when resuming an execution task", async () => {
  1055. const { agent, service, taskIndexRepo } = createService();
  1056. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1057. vi.mocked(agent.resumeSession).mockClear();
  1058. await service.resumeTask({
  1059. workspacePath: "/repo",
  1060. taskId: task.taskId,
  1061. automationId: "automation-2",
  1062. });
  1063. const resumeParams = vi.mocked(agent.resumeSession).mock.calls[0]?.[0];
  1064. expect(resumeParams).toEqual(
  1065. expect.objectContaining({
  1066. workspacePath: "/repo",
  1067. sessionId: task.taskId,
  1068. }),
  1069. );
  1070. expect(resumeParams).not.toHaveProperty("toolDenylist");
  1071. await expect(
  1072. taskIndexRepo.getTaskMeta({
  1073. workspacePath: "/repo",
  1074. taskId: task.taskId,
  1075. }),
  1076. ).resolves.toEqual(expect.objectContaining({ cronAutomationId: "automation-2" }));
  1077. });
  1078. it("marks automation execution prompts on v4 sendText commands", async () => {
  1079. const { agent, service } = createService();
  1080. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1081. vi.mocked(agent.sendConversationCommandV4).mockClear();
  1082. await service.sendPrompt({
  1083. taskId: task.taskId,
  1084. traceId: "trace-automation-run",
  1085. content: "run scheduled prompt",
  1086. automationId: "automation-1",
  1087. });
  1088. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith(
  1089. expect.objectContaining({
  1090. envelope: expect.objectContaining({
  1091. type: "sendText",
  1092. commandId: "trace-automation-run",
  1093. payload: {
  1094. text: "run scheduled prompt",
  1095. heldQueueDisposition: "keepQueueAndSend",
  1096. automationId: "automation-1",
  1097. toolDisallowlist: ["CronCreate", "CronUpdate", "CronDelete"],
  1098. },
  1099. }),
  1100. }),
  1101. );
  1102. });
  1103. it("applies a caller-scoped CronCreate denylist to a first-run prompt", async () => {
  1104. const { agent, service, taskIndexRepo } = createService();
  1105. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1106. vi.mocked(agent.sendConversationCommandV4).mockClear();
  1107. await service.sendPrompt({
  1108. taskId: task.taskId,
  1109. traceId: "trace-off-peak-first-run",
  1110. content: "run off-peak prompt",
  1111. offPeakTaskId: "offpeak-stable-1",
  1112. offPeakRunType: "init",
  1113. toolDenylist: ["CronCreate"],
  1114. });
  1115. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith(
  1116. expect.objectContaining({
  1117. envelope: expect.objectContaining({
  1118. type: "sendText",
  1119. commandId: "trace-off-peak-first-run",
  1120. payload: {
  1121. text: "run off-peak prompt",
  1122. heldQueueDisposition: "keepQueueAndSend",
  1123. offPeakTaskId: "offpeak-stable-1",
  1124. offPeakRunType: "init",
  1125. // D49-2:闲时派发轮在调用方 CronCreate 之外,纵深补 OffPeakCreate
  1126. // (免费池自我放大);OffPeakList 只读保留。
  1127. toolDisallowlist: ["CronCreate", "OffPeakCreate"],
  1128. },
  1129. }),
  1130. }),
  1131. );
  1132. await expect(
  1133. taskIndexRepo.getTaskMeta({
  1134. workspacePath: "/repo",
  1135. taskId: task.taskId,
  1136. }),
  1137. ).resolves.toEqual(expect.objectContaining({ cronAutomationId: undefined }));
  1138. });
  1139. it("applies a caller-scoped CronCreate denylist after resuming a normal session", async () => {
  1140. const { agent, service } = createService();
  1141. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1142. await service.resumeTask({ workspacePath: "/repo", taskId: task.taskId });
  1143. vi.mocked(agent.sendConversationCommandV4).mockClear();
  1144. await service.sendPrompt({
  1145. taskId: task.taskId,
  1146. traceId: "trace-off-peak-resume",
  1147. content: "continue off-peak prompt",
  1148. offPeakTaskId: "offpeak-stable-1",
  1149. offPeakRunType: "resume",
  1150. toolDenylist: ["CronCreate"],
  1151. });
  1152. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith(
  1153. expect.objectContaining({
  1154. envelope: expect.objectContaining({
  1155. type: "sendText",
  1156. commandId: "trace-off-peak-resume",
  1157. payload: {
  1158. text: "continue off-peak prompt",
  1159. heldQueueDisposition: "keepQueueAndSend",
  1160. offPeakTaskId: "offpeak-stable-1",
  1161. offPeakRunType: "resume",
  1162. // D49-2:续跑段与首跑同语义。
  1163. toolDisallowlist: ["CronCreate", "OffPeakCreate"],
  1164. },
  1165. }),
  1166. }),
  1167. );
  1168. });
  1169. it("restores automation mutation tools for a user turn in a cron-owned session", async () => {
  1170. const { agent, service } = createService();
  1171. // 会话因用户在其中创建过定时任务而归属 automation:DB meta 带 cronAutomationId。
  1172. const task = await service.createTask({
  1173. workspacePath: "/repo",
  1174. provider: "glm",
  1175. automationId: "automation-owned",
  1176. });
  1177. // 复刻打开已有定时任务会话:归属仍保存在 DB,但普通用户轮不携带 automationId。
  1178. await service.resumeTask({ workspacePath: "/repo", taskId: task.taskId });
  1179. service.onDynamicTaskEvent({
  1180. workspacePath: "/repo",
  1181. taskId: task.taskId,
  1182. deliveryKind: "continuous",
  1183. })(() => undefined);
  1184. vi.mocked(agent.sendConversationCommandV4).mockClear();
  1185. // 普通用户后续输入:不带 automationId。
  1186. await service.sendPrompt({
  1187. taskId: task.taskId,
  1188. traceId: "trace-followup",
  1189. content: "再帮我建一个每5分钟的提醒",
  1190. });
  1191. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith(
  1192. expect.objectContaining({
  1193. envelope: expect.objectContaining({
  1194. type: "sendText",
  1195. commandId: "trace-followup",
  1196. payload: {
  1197. text: "再帮我建一个每5分钟的提醒",
  1198. heldQueueDisposition: "keepQueueAndSend",
  1199. },
  1200. }),
  1201. }),
  1202. );
  1203. });
  1204. it("does not hide CronCreate for plain user turns in a normal (non cron-owned) session", async () => {
  1205. const { agent, service } = createService();
  1206. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1207. await service.resumeTask({ workspacePath: "/repo", taskId: task.taskId });
  1208. service.onDynamicTaskEvent({
  1209. workspacePath: "/repo",
  1210. taskId: task.taskId,
  1211. deliveryKind: "continuous",
  1212. })(() => undefined);
  1213. vi.mocked(agent.sendConversationCommandV4).mockClear();
  1214. await service.sendPrompt({
  1215. taskId: task.taskId,
  1216. traceId: "trace-normal",
  1217. content: "帮我看看这段代码",
  1218. });
  1219. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith(
  1220. expect.objectContaining({
  1221. envelope: expect.objectContaining({
  1222. type: "sendText",
  1223. commandId: "trace-normal",
  1224. payload: {
  1225. text: "帮我看看这段代码",
  1226. heldQueueDisposition: "keepQueueAndSend",
  1227. },
  1228. }),
  1229. }),
  1230. );
  1231. });
  1232. it("injects product CUA helper broker config before legacy createTask session creation", async () => {
  1233. // services 只负责建会话前把 MCP 配置交给 producer 的 resolver;改写细节由 producer 自己的测试覆盖。
  1234. // 这里用测试自己的 resolver,不依赖私有 producer 的注入实现(开源占位包不改写配置)。
  1235. const resolver = {
  1236. resolveMcpServers: vi.fn(async (servers) =>
  1237. servers?.map((server) =>
  1238. "command" in server
  1239. ? {
  1240. ...server,
  1241. args: [
  1242. ...(server.args ?? []),
  1243. "--permission-broker-socket",
  1244. "/tmp/zcode-cua/helper.sock",
  1245. ],
  1246. }
  1247. : server,
  1248. ),
  1249. ),
  1250. } satisfies CuaProductMcpServerResolver;
  1251. const { agent, service } = createService({ cuaProductMcpServerResolver: resolver });
  1252. await service.createTask({
  1253. workspacePath: "/repo",
  1254. provider: "glm",
  1255. mcpServers: [
  1256. {
  1257. name: ZCODE_CUA_OFFICIAL_MCP_NAMESPACE_NAME,
  1258. command: "uvx",
  1259. args: ["zcode-cua"],
  1260. env: [
  1261. { name: ZCODE_PLUGIN_ID_ENV_KEY, value: ZCODE_CUA_OFFICIAL_PLUGIN_ID },
  1262. { name: ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY, value: "test-authority" },
  1263. ],
  1264. },
  1265. ],
  1266. });
  1267. const createParams = vi.mocked(agent.createSession).mock.calls[0]?.[0];
  1268. const server = createParams?.mcpServers?.[0];
  1269. expect(resolver.resolveMcpServers).toHaveBeenCalledTimes(1);
  1270. expect(server && "command" in server ? server.args : []).toEqual([
  1271. "zcode-cua",
  1272. "--permission-broker-socket",
  1273. "/tmp/zcode-cua/helper.sock",
  1274. ]);
  1275. });
  1276. it("restarts only the current workspace agent process", async () => {
  1277. const { agent, service } = createService();
  1278. await service.restartWorkspaceProcess({
  1279. workspacePath: "/repo",
  1280. workspaceIdentity: "remote:ssh:dev:/repo",
  1281. provider: "glm",
  1282. });
  1283. // Bugfix: restartWorkspaceProcess 是切模型/配置后的 workspace 级重启,
  1284. // 不能调用 disposeAll 把整个 agent manager 永久关闭。
  1285. expect(agent.disposeWorkspace).toHaveBeenCalledWith({
  1286. workspacePath: "/repo",
  1287. workspaceIdentity: "remote:ssh:dev:/repo",
  1288. });
  1289. expect(agent.disposeAll).not.toHaveBeenCalled();
  1290. });
  1291. it("releases workspace preparation through the workspace-scoped agent lifecycle", async () => {
  1292. const { agent, service } = createService();
  1293. await service.releaseWorkspacePreparation({
  1294. workspacePath: "/repo",
  1295. workspaceIdentity: "remote:wsl:ubuntu:/repo",
  1296. provider: "glm",
  1297. });
  1298. expect(agent.disposeWorkspace).toHaveBeenCalledWith({
  1299. workspacePath: "/repo",
  1300. workspaceIdentity: "remote:wsl:ubuntu:/repo",
  1301. });
  1302. expect(agent.disposeAll).not.toHaveBeenCalled();
  1303. });
  1304. it("uses structured ModelSelection for a custom model", async () => {
  1305. const { agent, service } = createService();
  1306. const workspacePath = "/repo-custom-model-ref";
  1307. const task = await service.createTask({ workspacePath, provider: "glm" });
  1308. await service.setModel({
  1309. taskId: task.taskId,
  1310. traceId: "trace_custom_model_ref",
  1311. modelSelection: { providerId: "provider-b", modelId: "gpt-5.5" },
  1312. });
  1313. expect(agent.setModel).toHaveBeenCalledWith({
  1314. workspacePath,
  1315. workspaceIdentity: undefined,
  1316. sessionId: task.taskId,
  1317. model: { providerId: "provider-b", modelId: "gpt-5.5" },
  1318. });
  1319. });
  1320. it("records agent model network status events as HTTP network telemetry", async () => {
  1321. const observations: NetworkObservation[] = [];
  1322. setNetworkTelemetrySink((observation) => observations.push(observation));
  1323. const { eventEmitter, service } = createService();
  1324. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1325. const disposable = service.onDynamicTaskEvent({
  1326. workspacePath: "/repo",
  1327. taskId: task.taskId,
  1328. deliveryKind: "continuous",
  1329. })(() => undefined);
  1330. try {
  1331. eventEmitter.fire({
  1332. type: "session.event",
  1333. event: {
  1334. eventId: "evt-model-completed",
  1335. sessionId: task.taskId,
  1336. seq: 1,
  1337. timestamp: 1_700_000_000_000,
  1338. type: "session.updated",
  1339. payload: {
  1340. type: "model_request_completed",
  1341. timestamp: "2026-06-05T00:00:00.000Z",
  1342. traceId: "trace-model-network",
  1343. requestId: "request-model-network",
  1344. model: { providerId: "glm", modelId: "glm-4.6" },
  1345. baseURL: "https://api.example.com/v1?token=secret",
  1346. providerKind: "openai-compatible",
  1347. transport: "sse",
  1348. attempt: 2,
  1349. maxAttempts: 3,
  1350. durationMs: 456,
  1351. },
  1352. },
  1353. });
  1354. } finally {
  1355. disposable.dispose();
  1356. }
  1357. expect(observations).toEqual([
  1358. {
  1359. transport: "http",
  1360. interface: "zcode_agent.model.openai-compatible.sse.api.example.com/v1",
  1361. durationMs: 456,
  1362. ok: true,
  1363. attempt: 2,
  1364. },
  1365. ]);
  1366. });
  1367. it("projects user input response to elicitation response in dynamic task fallback subscriptions", async () => {
  1368. const { eventEmitter, service } = createService();
  1369. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1370. const streamEvents: ZCodeStreamEvent[] = [];
  1371. const disposable = service.onDynamicTaskEvent({
  1372. workspacePath: "/repo",
  1373. taskId: task.taskId,
  1374. deliveryKind: "continuous",
  1375. })((event) => {
  1376. streamEvents.push(event);
  1377. });
  1378. try {
  1379. eventEmitter.fire({
  1380. type: "userInput.response",
  1381. requestId: "input-1",
  1382. response: {
  1383. action: "accept",
  1384. content: { answers: { answer_0: "a" } },
  1385. },
  1386. });
  1387. } finally {
  1388. disposable.dispose();
  1389. }
  1390. expect(streamEvents).toContainEqual(
  1391. expect.objectContaining({
  1392. type: "elicitation_response",
  1393. taskId: task.taskId,
  1394. requestId: "input-1",
  1395. action: "accept",
  1396. content: { answers: { answer_0: "a" } },
  1397. }),
  1398. );
  1399. });
  1400. it("projects structured turn failure codes into dynamic task errors", async () => {
  1401. const { eventEmitter, service, taskIndexRepo } = createService();
  1402. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1403. const streamEvents: ZCodeStreamEvent[] = [];
  1404. const disposable = service.onDynamicTaskEvent({
  1405. workspacePath: "/repo",
  1406. taskId: task.taskId,
  1407. deliveryKind: "continuous",
  1408. })((event) => {
  1409. streamEvents.push(event);
  1410. });
  1411. try {
  1412. eventEmitter.fire({
  1413. type: "session.event",
  1414. event: {
  1415. eventId: "evt_turn_failed",
  1416. sessionId: task.taskId,
  1417. turnId: "turn_1",
  1418. seq: 1,
  1419. timestamp: 10,
  1420. traceId: "protocol_trace_1",
  1421. type: "turn.failed",
  1422. payload: {
  1423. turnPhase: "model",
  1424. inputId: "input_failed_1",
  1425. error: {
  1426. type: "MODEL_ERROR",
  1427. code: "provider_not_found",
  1428. message: "Model provider is not configured: stale-provider",
  1429. detail: "stale-provider/gpt-5.5",
  1430. attribution: {
  1431. source: "runtime",
  1432. reason: "provider_not_configured",
  1433. providerId: "account:zai-individual-coding-plan",
  1434. },
  1435. },
  1436. },
  1437. },
  1438. });
  1439. } finally {
  1440. disposable.dispose();
  1441. }
  1442. expect(streamEvents).toContainEqual(
  1443. expect.objectContaining({
  1444. type: "task_error",
  1445. taskId: task.taskId,
  1446. traceId: "input_failed_1",
  1447. inputId: "input_failed_1",
  1448. error: "Model provider is not configured: stale-provider",
  1449. code: "provider_not_found",
  1450. detail: "stale-provider/gpt-5.5",
  1451. attribution: {
  1452. source: "runtime",
  1453. reason: "provider_not_configured",
  1454. providerId: "account:zai-individual-coding-plan",
  1455. },
  1456. }),
  1457. );
  1458. // 旧 stream 适配只负责转发错误,不能作为第二个 task index 写者。
  1459. expect(
  1460. await taskIndexRepo.getTaskMeta({ workspacePath: "/repo", taskId: task.taskId }),
  1461. ).toMatchObject({ updatedAt: task.updatedAt, title: task.title });
  1462. });
  1463. it("projects streaming Write input in dynamic task fallback subscriptions", async () => {
  1464. const { eventEmitter, service } = createService();
  1465. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1466. const streamEvents: ZCodeStreamEvent[] = [];
  1467. const disposable = service.onDynamicTaskEvent({
  1468. workspacePath: "/repo",
  1469. taskId: task.taskId,
  1470. deliveryKind: "continuous",
  1471. })((event) => {
  1472. streamEvents.push(event);
  1473. });
  1474. try {
  1475. eventEmitter.fire({
  1476. type: "session.event",
  1477. event: {
  1478. eventId: "evt_turn_started",
  1479. sessionId: task.taskId,
  1480. turnId: "turn_1",
  1481. seq: 1,
  1482. timestamp: 10,
  1483. traceId: "protocol_trace_1",
  1484. type: "turn.started",
  1485. payload: {
  1486. input: "write file",
  1487. inputId: "input_write_1",
  1488. turnNumber: 1,
  1489. },
  1490. },
  1491. });
  1492. eventEmitter.fire({
  1493. type: "session.event",
  1494. event: {
  1495. eventId: "evt_tool_input_delta_1",
  1496. sessionId: task.taskId,
  1497. turnId: "turn_1",
  1498. seq: 2,
  1499. timestamp: 11,
  1500. traceId: "protocol_trace_1",
  1501. type: "model.streaming",
  1502. payload: {
  1503. kind: "tool_input_delta",
  1504. toolCallId: "call_write",
  1505. delta: '{"file_path":"src/app.ts","content":"line 1',
  1506. },
  1507. },
  1508. });
  1509. eventEmitter.fire({
  1510. type: "session.event",
  1511. event: {
  1512. eventId: "evt_tool_input_delta_2",
  1513. sessionId: task.taskId,
  1514. turnId: "turn_1",
  1515. seq: 3,
  1516. timestamp: 12,
  1517. traceId: "protocol_trace_1",
  1518. type: "model.streaming",
  1519. payload: {
  1520. kind: "tool_input_delta",
  1521. toolCallId: "call_write",
  1522. delta: "\\nline 2",
  1523. },
  1524. },
  1525. });
  1526. eventEmitter.fire({
  1527. type: "session.event",
  1528. event: {
  1529. eventId: "evt_tool_call_final",
  1530. sessionId: task.taskId,
  1531. turnId: "turn_1",
  1532. seq: 4,
  1533. timestamp: 13,
  1534. traceId: "protocol_trace_1",
  1535. type: "model.streaming",
  1536. payload: {
  1537. kind: "tool_call",
  1538. toolCallId: "call_write",
  1539. toolName: "Write",
  1540. input: {
  1541. file_path: "src/app.ts",
  1542. content: "line 1\nline 2",
  1543. },
  1544. },
  1545. },
  1546. });
  1547. } finally {
  1548. disposable.dispose();
  1549. }
  1550. const runStarted = streamEvents.find((event) => event.type === "task_run_started");
  1551. const toolUpdates = streamEvents.filter(
  1552. (event): event is Extract<ZCodeStreamEvent, { type: "tool_call_update" }> =>
  1553. event.type === "tool_call_update",
  1554. );
  1555. expect(runStarted).toMatchObject({
  1556. type: "task_run_started",
  1557. traceId: "input_write_1",
  1558. inputId: "input_write_1",
  1559. });
  1560. expect(toolUpdates.at(-1)).toMatchObject({
  1561. type: "tool_call_update",
  1562. traceId: "input_write_1",
  1563. inputId: "input_write_1",
  1564. toolId: "call_write",
  1565. toolName: "Write",
  1566. kind: "Write",
  1567. title: "Write",
  1568. input: {
  1569. file_path: "src/app.ts",
  1570. content: "line 1\nline 2",
  1571. },
  1572. });
  1573. });
  1574. it("keeps background Agent launch acknowledgements in progress in dynamic task streams", async () => {
  1575. const { eventEmitter, service } = createService();
  1576. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1577. const streamEvents: ZCodeStreamEvent[] = [];
  1578. const disposable = service.onDynamicTaskEvent({
  1579. workspacePath: "/repo",
  1580. taskId: task.taskId,
  1581. deliveryKind: "continuous",
  1582. })((event) => {
  1583. streamEvents.push(event);
  1584. });
  1585. try {
  1586. eventEmitter.fire({
  1587. type: "session.event",
  1588. event: {
  1589. eventId: "evt_parent_agent",
  1590. sessionId: task.taskId,
  1591. turnId: "turn_1",
  1592. seq: 1,
  1593. timestamp: 10,
  1594. traceId: "trace_session",
  1595. type: "tool.updated",
  1596. payload: {
  1597. kind: "scheduled",
  1598. toolCallId: "call_parent_agent",
  1599. toolName: "Agent",
  1600. input: {
  1601. description: "Inspect workspace",
  1602. prompt: "Find the project shape",
  1603. run_in_background: true,
  1604. },
  1605. },
  1606. },
  1607. });
  1608. eventEmitter.fire({
  1609. type: "session.event",
  1610. event: {
  1611. eventId: "evt_parent_agent_result",
  1612. sessionId: task.taskId,
  1613. turnId: "turn_1",
  1614. seq: 2,
  1615. timestamp: 11,
  1616. traceId: "trace_session",
  1617. type: "tool.updated",
  1618. payload: {
  1619. kind: "result",
  1620. toolCallId: "call_parent_agent",
  1621. duration: 4,
  1622. result: {
  1623. success: true,
  1624. content: [
  1625. 'Agent Explore task "Inspect workspace" started in background.',
  1626. "agentId: agent_1",
  1627. "backgroundTaskId: agent_1",
  1628. "Runtime will wait for this background Agent before completing the current turn.",
  1629. ].join("\n"),
  1630. },
  1631. },
  1632. },
  1633. });
  1634. } finally {
  1635. disposable.dispose();
  1636. }
  1637. expect(streamEvents).toContainEqual(
  1638. expect.objectContaining({
  1639. type: "tool_call_update",
  1640. toolId: "call_parent_agent",
  1641. toolName: "Agent",
  1642. status: "in_progress",
  1643. }),
  1644. );
  1645. });
  1646. it("keeps previous and current async Task launch acknowledgements in progress in dynamic task streams", async () => {
  1647. const { eventEmitter, service } = createService();
  1648. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1649. const streamEvents: ZCodeStreamEvent[] = [];
  1650. const disposable = service.onDynamicTaskEvent({
  1651. workspacePath: "/repo",
  1652. taskId: task.taskId,
  1653. deliveryKind: "continuous",
  1654. })((event) => {
  1655. streamEvents.push(event);
  1656. });
  1657. try {
  1658. const acknowledgementContents = [
  1659. [
  1660. 'Agent general-purpose task "Inspect workspace" started in background.',
  1661. "agentId: agent_1",
  1662. "outputFile: /tmp/agent_1/output.txt",
  1663. "You will be notified when the Agent completes.",
  1664. ].join("\n"),
  1665. [
  1666. "Async agent launched successfully.",
  1667. "agentId: agent_1 (internal ID - do not mention to user. Use SendMessage with to: 'agent_1' to continue this agent.)",
  1668. "The agent is working in the background. You will be notified automatically when it completes.",
  1669. "output_file: /tmp/agent_1/output.txt",
  1670. "Do NOT Read or tail this file via the shell tool.",
  1671. ].join("\n"),
  1672. ];
  1673. for (const [index, content] of acknowledgementContents.entries()) {
  1674. const toolCallId = `call_parent_task_${index}`;
  1675. eventEmitter.fire({
  1676. type: "session.event",
  1677. event: {
  1678. eventId: `evt_parent_task_${index}`,
  1679. sessionId: task.taskId,
  1680. turnId: "turn_1",
  1681. seq: index * 2 + 1,
  1682. timestamp: 10 + index * 2,
  1683. traceId: "trace_session",
  1684. type: "tool.updated",
  1685. payload: {
  1686. kind: "scheduled",
  1687. toolCallId,
  1688. toolName: "Task",
  1689. input: {
  1690. description: "Inspect workspace",
  1691. prompt: "Find the project shape",
  1692. },
  1693. },
  1694. },
  1695. });
  1696. eventEmitter.fire({
  1697. type: "session.event",
  1698. event: {
  1699. eventId: `evt_parent_task_result_${index}`,
  1700. sessionId: task.taskId,
  1701. turnId: "turn_1",
  1702. seq: index * 2 + 2,
  1703. timestamp: 11 + index * 2,
  1704. traceId: "trace_session",
  1705. type: "tool.updated",
  1706. payload: {
  1707. kind: "result",
  1708. toolCallId,
  1709. duration: 4,
  1710. result: {
  1711. success: true,
  1712. content,
  1713. },
  1714. },
  1715. },
  1716. });
  1717. }
  1718. } finally {
  1719. disposable.dispose();
  1720. }
  1721. for (let index = 0; index < 2; index++) {
  1722. expect(streamEvents).toContainEqual(
  1723. expect.objectContaining({
  1724. type: "tool_call_update",
  1725. toolId: `call_parent_task_${index}`,
  1726. toolName: "Task",
  1727. status: "in_progress",
  1728. }),
  1729. );
  1730. }
  1731. });
  1732. // M5 ③ 删除:listWorkspaceTaskLists(workspace 行分组查询)——列表面(本机 + remote shard)
  1733. // 已切 sessions-index,分组结果在客户端由 sessions + tasks-index 归属 join 构建。
  1734. it("broadcasts task_created when createTask inserts a new indexed task", async () => {
  1735. const { service } = createService();
  1736. const events: Array<{ reason?: string; taskId?: string }> = [];
  1737. const disposable = service.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) => {
  1738. if (event.type === "workspace_task_list_changed") {
  1739. events.push({ reason: event.reason, taskId: event.taskMeta?.taskId });
  1740. }
  1741. });
  1742. await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1743. disposable.dispose();
  1744. expect(events).toEqual([
  1745. {
  1746. reason: "task_created",
  1747. taskId: "sess_1",
  1748. },
  1749. ]);
  1750. });
  1751. it("broadcasts explicit task list membership reasons for pin and archive actions", async () => {
  1752. const { service } = createService();
  1753. const events: Array<{ reason?: string; taskId?: string }> = [];
  1754. const disposable = service.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) => {
  1755. if (event.type === "workspace_task_list_changed") {
  1756. events.push({ reason: event.reason, taskId: event.taskMeta?.taskId });
  1757. }
  1758. });
  1759. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1760. await service.setTaskPinned({
  1761. workspacePath: "/repo",
  1762. taskId: task.taskId,
  1763. pinned: true,
  1764. });
  1765. await service.setTaskPinned({
  1766. workspacePath: "/repo",
  1767. taskId: task.taskId,
  1768. pinned: false,
  1769. });
  1770. await service.archiveTask({
  1771. workspacePath: "/repo",
  1772. taskId: task.taskId,
  1773. });
  1774. await service.unarchiveTask({
  1775. workspacePath: "/repo",
  1776. taskId: task.taskId,
  1777. });
  1778. disposable.dispose();
  1779. expect(events).toEqual([
  1780. { reason: "task_created", taskId: task.taskId },
  1781. { reason: "task_pinned", taskId: task.taskId },
  1782. { reason: "task_unpinned", taskId: task.taskId },
  1783. { reason: "task_archived", taskId: task.taskId },
  1784. { reason: "task_unarchived", taskId: task.taskId },
  1785. ]);
  1786. });
  1787. it("does not clear a newer unread marker when the system clock does not advance", async () => {
  1788. vi.useFakeTimers();
  1789. const { service, taskIndexRepo } = createService();
  1790. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1791. vi.setSystemTime(100);
  1792. const [openedUnread, terminalUnread] = await Promise.all([
  1793. service.setTaskUnread({
  1794. workspacePath: "/repo",
  1795. taskId: task.taskId,
  1796. unread: true,
  1797. }),
  1798. service.setTaskUnread({
  1799. workspacePath: "/repo",
  1800. taskId: task.taskId,
  1801. unread: true,
  1802. }),
  1803. ]);
  1804. expect(openedUnread.unreadAt).toBe(100);
  1805. expect(terminalUnread.unreadAt).toBe(101);
  1806. await expect(
  1807. service.getTaskSnapshot({
  1808. workspacePath: "/repo",
  1809. taskId: task.taskId,
  1810. }),
  1811. ).resolves.toEqual(
  1812. expect.objectContaining({ meta: expect.objectContaining({ unreadAt: 101 }) }),
  1813. );
  1814. const events: string[] = [];
  1815. const disposable = service.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) => {
  1816. if (event.type === "workspace_task_list_changed") {
  1817. events.push(event.reason);
  1818. }
  1819. });
  1820. const result = await service.setTaskUnread({
  1821. workspacePath: "/repo",
  1822. taskId: task.taskId,
  1823. unread: false,
  1824. expectedUnreadAt: openedUnread.unreadAt,
  1825. });
  1826. expect(result.unreadAt).toBe(terminalUnread.unreadAt);
  1827. await expect(
  1828. taskIndexRepo.getTaskMeta({
  1829. workspacePath: "/repo",
  1830. taskId: task.taskId,
  1831. }),
  1832. ).resolves.toEqual(expect.objectContaining({ unreadAt: terminalUnread.unreadAt }));
  1833. expect(events).toEqual([]);
  1834. await service.setTaskUnread({
  1835. workspacePath: "/repo",
  1836. taskId: task.taskId,
  1837. unread: false,
  1838. expectedUnreadAt: terminalUnread.unreadAt,
  1839. });
  1840. events.length = 0;
  1841. const unreadAfterClear = await service.setTaskUnread({
  1842. workspacePath: "/repo",
  1843. taskId: task.taskId,
  1844. unread: true,
  1845. });
  1846. expect(unreadAfterClear.unreadAt).toBe(102);
  1847. events.length = 0;
  1848. const staleClearAfterNewUnread = await service.setTaskUnread({
  1849. workspacePath: "/repo",
  1850. taskId: task.taskId,
  1851. unread: false,
  1852. expectedUnreadAt: terminalUnread.unreadAt,
  1853. });
  1854. disposable.dispose();
  1855. expect(staleClearAfterNewUnread.unreadAt).toBe(unreadAfterClear.unreadAt);
  1856. expect(events).toEqual([]);
  1857. });
  1858. it("clears the unread marker when expectedUnreadAt still matches", async () => {
  1859. vi.useFakeTimers();
  1860. vi.setSystemTime(100);
  1861. const { service, taskIndexRepo } = createService();
  1862. await seedIndexedTask(taskIndexRepo, {
  1863. taskId: "matching-read-clear",
  1864. provider: "glm",
  1865. });
  1866. const openedUnread = await service.setTaskUnread({
  1867. workspacePath: "/repo",
  1868. taskId: "matching-read-clear",
  1869. unread: true,
  1870. });
  1871. const events: string[] = [];
  1872. const disposable = service.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) => {
  1873. if (event.type === "workspace_task_list_changed") {
  1874. events.push(event.reason);
  1875. }
  1876. });
  1877. const result = await service.setTaskUnread({
  1878. workspacePath: "/repo",
  1879. taskId: "matching-read-clear",
  1880. unread: false,
  1881. expectedUnreadAt: openedUnread.unreadAt,
  1882. });
  1883. disposable.dispose();
  1884. expect(result.unreadAt).toBeUndefined();
  1885. const persisted = await taskIndexRepo.getTaskMeta({
  1886. workspacePath: "/repo",
  1887. taskId: "matching-read-clear",
  1888. });
  1889. expect(persisted?.unreadAt).toBeUndefined();
  1890. expect(events).toEqual(["task_meta_changed"]);
  1891. });
  1892. it("keeps task facts unchanged when CLI rejects rename or deletion", async () => {
  1893. const { agent, service, taskIndexRepo } = createService();
  1894. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1895. vi.mocked(agent.sendConversationCommandV4).mockRejectedValue(new Error("offline"));
  1896. await expect(service.renameTask({ ...task, title: "must not persist" })).rejects.toThrow(
  1897. "offline",
  1898. );
  1899. await expect(service.deleteTask(task)).rejects.toThrow("offline");
  1900. expect(await taskIndexRepo.getTaskMeta(task)).toMatchObject({
  1901. title: task.title,
  1902. updatedAt: task.updatedAt,
  1903. });
  1904. expect(await service.listDeletedTaskIds({ workspacePath: "/repo" })).toEqual([]);
  1905. });
  1906. it("deletes through CLI before mirroring its durable tombstone", async () => {
  1907. const { agent, service, taskIndexRepo } = createService();
  1908. const events: Array<{ reason?: string; taskId?: string }> = [];
  1909. const disposable = service.onDynamicWorkspaceEvent({ workspacePath: "/repo" })((event) => {
  1910. if (event.type === "workspace_task_list_changed") {
  1911. events.push({ reason: event.reason, taskId: event.taskId ?? event.taskMeta?.taskId });
  1912. }
  1913. });
  1914. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  1915. await service.archiveTask({ workspacePath: "/repo", taskId: task.taskId });
  1916. vi.mocked(agent.sendConversationCommandV4).mockClear();
  1917. agent.reconcileSessionsIndexV4 = vi.fn(async () => ({
  1918. sessions: [
  1919. {
  1920. sessionId: task.taskId,
  1921. exists: true as const,
  1922. deleted: true,
  1923. title: task.title,
  1924. titleSource: "default" as const,
  1925. createdAt: task.createdAt,
  1926. updatedAt: task.updatedAt,
  1927. },
  1928. ],
  1929. }));
  1930. await service.deleteTask({ workspacePath: "/repo", taskId: task.taskId });
  1931. disposable.dispose();
  1932. await expect(service.listDeletedTaskIds({ workspacePath: "/repo" })).resolves.toEqual([
  1933. task.taskId,
  1934. ]);
  1935. await expect(service.listArchivedTasks({ workspacePath: "/repo" })).resolves.toEqual([]);
  1936. await expect(
  1937. taskIndexRepo.listTaskMetas({
  1938. workspacePath: "/repo",
  1939. provider: "glm",
  1940. archived: true,
  1941. includeDeleted: true,
  1942. }),
  1943. ).resolves.toEqual([expect.objectContaining({ taskId: task.taskId })]);
  1944. expect(events.at(-1)).toEqual({ reason: "task_deleted", taskId: task.taskId });
  1945. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith(
  1946. expect.objectContaining({ envelope: expect.objectContaining({ type: "deleteSession" }) }),
  1947. );
  1948. });
  1949. it("renames through CLI while preserving CLI activity time", async () => {
  1950. vi.useFakeTimers();
  1951. vi.setSystemTime(new Date("2026-06-13T14:45:00.000Z"));
  1952. const { agent, service, taskIndexRepo } = createService();
  1953. await seedIndexedTask(taskIndexRepo, {
  1954. taskId: "running-rename",
  1955. provider: "glm",
  1956. workspacePath: "/repo",
  1957. updatedAt: 100,
  1958. });
  1959. vi.mocked(agent.sendConversationCommandV4).mockClear();
  1960. agent.reconcileSessionsIndexV4 = vi.fn(async () => ({
  1961. sessions: [
  1962. {
  1963. sessionId: "running-rename",
  1964. exists: true as const,
  1965. deleted: false,
  1966. title: "短名",
  1967. titleSource: "custom" as const,
  1968. createdAt: 1,
  1969. updatedAt: 100,
  1970. },
  1971. ],
  1972. }));
  1973. const renamed = await service.renameTask({
  1974. taskId: "running-rename",
  1975. workspacePath: "/repo",
  1976. title: "短名",
  1977. });
  1978. expect(renamed.title).toBe("短名");
  1979. expect(renamed.titleOverridden).toBe(true);
  1980. expect(renamed.updatedAt).toBe(100);
  1981. await expect(
  1982. taskIndexRepo.getTaskMeta({
  1983. taskId: "running-rename",
  1984. workspacePath: "/repo",
  1985. }),
  1986. ).resolves.toMatchObject({
  1987. title: "短名",
  1988. titleOverridden: true,
  1989. });
  1990. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith({
  1991. workspacePath: "/repo",
  1992. workspaceIdentity: undefined,
  1993. envelope: expect.objectContaining({
  1994. type: "renameSession",
  1995. sessionId: "running-rename",
  1996. payload: { title: "短名" },
  1997. }),
  1998. });
  1999. });
  2000. it("reads the bound Session original selection without filtering unavailable model options", async () => {
  2001. const { agent, service } = createService();
  2002. const workspaceIdentity = "remote:ssh:dev:/repo";
  2003. const task = await service.createTask({
  2004. workspacePath: "/repo",
  2005. workspaceIdentity,
  2006. provider: "glm",
  2007. });
  2008. const original = {
  2009. providerId: "account:bigmodel-individual-coding-plan",
  2010. modelId: "removed-model",
  2011. options: { reasoningLevel: "removed-level" },
  2012. };
  2013. const snapshot = makeSnapshot({
  2014. sessionId: task.taskId,
  2015. workspacePath: "/repo",
  2016. workspaceIdentity,
  2017. model: original,
  2018. });
  2019. snapshot.settings.model.available = [];
  2020. snapshot.settings.thoughtLevel.current = undefined;
  2021. vi.mocked(agent.readSession).mockResolvedValueOnce(snapshot);
  2022. vi.mocked(agent.setModel).mockClear();
  2023. expect(await service.getTaskModelSelection({ taskId: task.taskId })).toEqual(original);
  2024. expect(agent.readSession).toHaveBeenLastCalledWith({
  2025. workspacePath: "/repo",
  2026. workspaceIdentity,
  2027. sessionId: task.taskId,
  2028. });
  2029. expect(agent.setModel).not.toHaveBeenCalled();
  2030. });
  2031. it("creates a Bot draft with the native v4 createSession command", async () => {
  2032. const { agent, service } = createService();
  2033. const mcpServers = [{ name: "docs", command: "node", args: ["server.js"], env: [] }];
  2034. const task = await service.createTask({
  2035. workspacePath: "/repo",
  2036. provider: "glm",
  2037. model: "glm/deepseek-v4-flash",
  2038. mcpServers,
  2039. v4Create: true,
  2040. });
  2041. expect(agent.createSession).not.toHaveBeenCalled();
  2042. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith({
  2043. workspacePath: "/repo",
  2044. workspaceIdentity: undefined,
  2045. projectId: null,
  2046. envelope: expect.objectContaining({
  2047. sessionId: null,
  2048. type: "createSession",
  2049. payload: expect.objectContaining({
  2050. workspaceId: "/repo",
  2051. config: expect.objectContaining({
  2052. provider: "glm",
  2053. model: "deepseek-v4-flash",
  2054. }),
  2055. mcpServers,
  2056. }),
  2057. }),
  2058. });
  2059. expect(task.taskId).toBe("sess_v4_created");
  2060. });
  2061. it("desktop-attached remote Bot draft 只发送 ModelSelection", async () => {
  2062. const { agent, service } = createService();
  2063. await service.createTask({
  2064. workspacePath: "/repo",
  2065. workspaceIdentity: "remote:ssh:dev:/repo",
  2066. provider: "glm",
  2067. model: "alternate-provider/deepseek-v4-pro",
  2068. v4Create: true,
  2069. });
  2070. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith(
  2071. expect.objectContaining({
  2072. workspaceIdentity: "remote:ssh:dev:/repo",
  2073. envelope: expect.objectContaining({
  2074. type: "createSession",
  2075. payload: expect.objectContaining({
  2076. config: expect.objectContaining({
  2077. provider: "alternate-provider",
  2078. model: "deepseek-v4-pro",
  2079. }),
  2080. }),
  2081. }),
  2082. }),
  2083. );
  2084. const command = vi.mocked(agent.sendConversationCommandV4).mock.calls.at(-1)?.[0];
  2085. expect(command?.envelope.payload).not.toHaveProperty("runtimeModel");
  2086. });
  2087. it("uses deferred persistence and disables generated titles only for automation sessions", async () => {
  2088. const { agent, service } = createService();
  2089. await service.createTask({
  2090. workspacePath: "/repo",
  2091. provider: "glm",
  2092. automationId: "automation_1",
  2093. });
  2094. expect(agent.createSession).toHaveBeenLastCalledWith(
  2095. expect.objectContaining({
  2096. persistence: "deferred",
  2097. titleGenerationEnabled: false,
  2098. }),
  2099. );
  2100. await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2101. const regularCreate = vi.mocked(agent.createSession).mock.calls.at(-1)?.[0];
  2102. expect(regularCreate).not.toHaveProperty("titleGenerationEnabled");
  2103. expect(regularCreate).not.toHaveProperty("persistence");
  2104. });
  2105. it("uses deferred persistence without cron metadata for headless first-prompt sessions", async () => {
  2106. const { agent, service } = createService();
  2107. const task = await service.createTask({
  2108. workspacePath: "/repo",
  2109. provider: "glm",
  2110. deferPersistenceUntilFirstPrompt: true,
  2111. });
  2112. expect(agent.createSession).toHaveBeenLastCalledWith(
  2113. expect.objectContaining({
  2114. persistence: "deferred",
  2115. }),
  2116. );
  2117. expect(vi.mocked(agent.createSession).mock.calls.at(-1)?.[0]).not.toHaveProperty(
  2118. "titleGenerationEnabled",
  2119. );
  2120. expect(task.cronAutomationId).toBeUndefined();
  2121. });
  2122. it("drains an accepted mobile task command after the current turn completes", async () => {
  2123. const { agent, eventEmitter, indexFrameEmitter, service } = createService();
  2124. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2125. const disposable = service.onDynamicTaskEvent({
  2126. workspacePath: "/repo",
  2127. taskId: task.taskId,
  2128. deliveryKind: "replayable",
  2129. })(() => undefined);
  2130. try {
  2131. await service.sendPrompt({
  2132. taskId: task.taskId,
  2133. traceId: "input_first",
  2134. queryId: "query_first",
  2135. content: "first",
  2136. });
  2137. await service.enqueueTaskCommand({
  2138. workspacePath: "/repo",
  2139. taskId: task.taskId,
  2140. commandId: "queued_second",
  2141. traceId: "input_second",
  2142. queryId: "query_second",
  2143. type: "send_prompt",
  2144. content: "second",
  2145. });
  2146. expect(agent.sendConversationCommandV4).toHaveBeenCalledTimes(1);
  2147. eventEmitter.fire({
  2148. type: "session.event",
  2149. event: {
  2150. eventId: "evt_turn_completed",
  2151. sessionId: task.taskId,
  2152. turnId: "turn_first",
  2153. seq: 2,
  2154. timestamp: 100,
  2155. traceId: "protocol_trace_first",
  2156. type: "turn.completed",
  2157. payload: {
  2158. inputId: "input_first",
  2159. response: "done",
  2160. },
  2161. },
  2162. });
  2163. await flushMicrotasks();
  2164. expect(agent.sendConversationCommandV4).toHaveBeenCalledTimes(1);
  2165. await firePromptCompletedState(indexFrameEmitter, {
  2166. sessionId: task.taskId,
  2167. workspacePath: "/repo",
  2168. });
  2169. await flushMicrotasks();
  2170. expect(agent.sendConversationCommandV4).toHaveBeenCalledTimes(2);
  2171. // 幂等键 inputId→commandId:drain 落 v4 sendText,终态收口仍按 traceId 对账。
  2172. expect(agent.sendConversationCommandV4).toHaveBeenLastCalledWith({
  2173. workspacePath: "/repo",
  2174. workspaceIdentity: undefined,
  2175. envelope: expect.objectContaining({
  2176. type: "sendText",
  2177. sessionId: task.taskId,
  2178. commandId: "input_second",
  2179. payload: { text: "second", heldQueueDisposition: "keepQueueAndSend" },
  2180. }),
  2181. });
  2182. } finally {
  2183. disposable.dispose();
  2184. }
  2185. });
  2186. it("drains automation host command with CronCreate denied", async () => {
  2187. const { agent, eventEmitter, indexFrameEmitter, service } = createService();
  2188. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2189. await service.sendPrompt({
  2190. taskId: task.taskId,
  2191. traceId: "input_first",
  2192. queryId: "query_first",
  2193. content: "first",
  2194. });
  2195. const result = await service.enqueueTaskCommand({
  2196. workspacePath: "/repo",
  2197. taskId: task.taskId,
  2198. commandId: "queued_automation",
  2199. traceId: "automation-parent:manual:run-1",
  2200. queryId: "automation-parent:manual:run-1",
  2201. type: "send_prompt",
  2202. content: "每 5 分钟给我讲个冷笑话",
  2203. automationId: "automation-parent",
  2204. });
  2205. expect(result.command).toEqual(
  2206. expect.objectContaining({
  2207. automationId: "automation-parent",
  2208. status: "accepted",
  2209. }),
  2210. );
  2211. expect(agent.sendConversationCommandV4).toHaveBeenCalledTimes(1);
  2212. eventEmitter.fire({
  2213. type: "session.event",
  2214. event: {
  2215. eventId: "evt_turn_completed",
  2216. sessionId: task.taskId,
  2217. turnId: "turn_first",
  2218. seq: 2,
  2219. timestamp: 100,
  2220. traceId: "protocol_trace_first",
  2221. type: "turn.completed",
  2222. payload: {
  2223. inputId: "input_first",
  2224. response: "done",
  2225. },
  2226. },
  2227. });
  2228. await flushMicrotasks();
  2229. await firePromptCompletedState(indexFrameEmitter, {
  2230. sessionId: task.taskId,
  2231. workspacePath: "/repo",
  2232. });
  2233. await flushMicrotasks();
  2234. expect(agent.sendConversationCommandV4).toHaveBeenCalledTimes(2);
  2235. expect(agent.sendConversationCommandV4).toHaveBeenLastCalledWith({
  2236. workspacePath: "/repo",
  2237. workspaceIdentity: undefined,
  2238. envelope: expect.objectContaining({
  2239. type: "sendText",
  2240. sessionId: task.taskId,
  2241. commandId: "automation-parent:manual:run-1",
  2242. payload: {
  2243. text: "每 5 分钟给我讲个冷笑话",
  2244. heldQueueDisposition: "keepQueueAndSend",
  2245. automationId: "automation-parent",
  2246. toolDisallowlist: ["CronCreate", "CronUpdate", "CronDelete"],
  2247. },
  2248. }),
  2249. });
  2250. });
  2251. it("drains a mobile task command when the session syncer observes the ready event", async () => {
  2252. const { agent, eventEmitter, indexFrameEmitter, service } = createService();
  2253. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2254. await service.sendPrompt({
  2255. taskId: task.taskId,
  2256. traceId: "input_first",
  2257. queryId: "query_first",
  2258. content: "first",
  2259. });
  2260. await service.enqueueTaskCommand({
  2261. workspacePath: "/repo",
  2262. taskId: task.taskId,
  2263. commandId: "queued_second",
  2264. traceId: "input_second",
  2265. queryId: "query_second",
  2266. type: "send_prompt",
  2267. content: "second",
  2268. });
  2269. expect(agent.sendConversationCommandV4).toHaveBeenCalledTimes(1);
  2270. eventEmitter.fire({
  2271. type: "session.event",
  2272. event: {
  2273. eventId: "evt_turn_completed",
  2274. sessionId: task.taskId,
  2275. turnId: "turn_first",
  2276. seq: 2,
  2277. timestamp: 100,
  2278. traceId: "protocol_trace_first",
  2279. type: "turn.completed",
  2280. payload: {
  2281. inputId: "input_first",
  2282. response: "done",
  2283. },
  2284. },
  2285. });
  2286. await flushMicrotasks();
  2287. expect(agent.sendConversationCommandV4).toHaveBeenCalledTimes(1);
  2288. await firePromptCompletedState(indexFrameEmitter, {
  2289. sessionId: task.taskId,
  2290. workspacePath: "/repo",
  2291. });
  2292. await flushMicrotasks();
  2293. expect(agent.sendConversationCommandV4).toHaveBeenCalledTimes(2);
  2294. // 幂等键 inputId→commandId:drain 落 v4 sendText,终态收口仍按 traceId 对账。
  2295. expect(agent.sendConversationCommandV4).toHaveBeenLastCalledWith({
  2296. workspacePath: "/repo",
  2297. workspaceIdentity: undefined,
  2298. envelope: expect.objectContaining({
  2299. type: "sendText",
  2300. sessionId: task.taskId,
  2301. commandId: "input_second",
  2302. payload: { text: "second", heldQueueDisposition: "keepQueueAndSend" },
  2303. }),
  2304. });
  2305. });
  2306. it("rejects a stale mobile enqueue command for an older owner run", async () => {
  2307. const { agent, service } = createService();
  2308. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2309. await service.sendPrompt({
  2310. taskId: task.taskId,
  2311. traceId: "input_current",
  2312. queryId: "query_current",
  2313. content: "current",
  2314. });
  2315. await expect(
  2316. service.enqueueTaskCommand({
  2317. workspacePath: "/repo",
  2318. taskId: task.taskId,
  2319. commandId: "queued_stale",
  2320. traceId: "input_stale_queued",
  2321. queryId: "query_stale_queued",
  2322. type: "send_prompt",
  2323. content: "stale queued",
  2324. ownerRunId: "input_old",
  2325. }),
  2326. ).rejects.toMatchObject({
  2327. code: "STALE_TASK_OWNER_COMMAND",
  2328. });
  2329. expect(agent.sendConversationCommandV4).toHaveBeenCalledTimes(1);
  2330. const snapshot = await service.getTaskSnapshot({
  2331. workspacePath: "/repo",
  2332. taskId: task.taskId,
  2333. clientMode: "web-remote-replayable",
  2334. });
  2335. expect(snapshot?.runtime?.pendingCommands).toEqual([]);
  2336. });
  2337. it("rejects a stale mobile promote command for an older owner run", async () => {
  2338. const { service } = createService();
  2339. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2340. await service.sendPrompt({
  2341. taskId: task.taskId,
  2342. traceId: "input_current",
  2343. queryId: "query_current",
  2344. content: "current",
  2345. });
  2346. await service.enqueueTaskCommand({
  2347. workspacePath: "/repo",
  2348. taskId: task.taskId,
  2349. commandId: "queued_second",
  2350. traceId: "input_second",
  2351. queryId: "query_second",
  2352. type: "send_prompt",
  2353. content: "second",
  2354. ownerRunId: "input_current",
  2355. });
  2356. await expect(
  2357. service.promoteTaskCommand({
  2358. workspacePath: "/repo",
  2359. taskId: task.taskId,
  2360. commandId: "queued_second",
  2361. ownerRunId: "input_old",
  2362. clientMode: "web-remote-replayable",
  2363. }),
  2364. ).rejects.toMatchObject({
  2365. code: "STALE_TASK_OWNER_COMMAND",
  2366. });
  2367. const snapshot = await service.getTaskSnapshot({
  2368. workspacePath: "/repo",
  2369. taskId: task.taskId,
  2370. clientMode: "web-remote-replayable",
  2371. });
  2372. expect(snapshot?.runtime?.pendingCommands).toEqual([
  2373. expect.objectContaining({
  2374. commandId: "queued_second",
  2375. status: "accepted",
  2376. traceId: "input_second",
  2377. }),
  2378. ]);
  2379. });
  2380. it("cancels an accepted mobile task command before it drains", async () => {
  2381. const { agent, indexFrameEmitter, service } = createService();
  2382. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2383. await service.sendPrompt({
  2384. taskId: task.taskId,
  2385. traceId: "input_current",
  2386. queryId: "query_current",
  2387. content: "current",
  2388. });
  2389. await service.enqueueTaskCommand({
  2390. workspacePath: "/repo",
  2391. taskId: task.taskId,
  2392. commandId: "queued_second",
  2393. traceId: "input_second",
  2394. queryId: "query_second",
  2395. type: "send_prompt",
  2396. content: "second",
  2397. ownerRunId: "input_current",
  2398. });
  2399. const result = await service.cancelTaskCommand({
  2400. workspacePath: "/repo",
  2401. taskId: task.taskId,
  2402. commandId: "queued_second",
  2403. ownerRunId: "input_current",
  2404. clientMode: "web-remote-replayable",
  2405. });
  2406. expect(result).toEqual(
  2407. expect.objectContaining({
  2408. canceled: true,
  2409. commandId: "queued_second",
  2410. status: "accepted",
  2411. }),
  2412. );
  2413. const snapshot = await service.getTaskSnapshot({
  2414. workspacePath: "/repo",
  2415. taskId: task.taskId,
  2416. clientMode: "web-remote-replayable",
  2417. });
  2418. expect(snapshot?.runtime?.pendingCommands).toEqual([]);
  2419. await firePromptCompletedState(indexFrameEmitter, {
  2420. sessionId: task.taskId,
  2421. workspacePath: "/repo",
  2422. });
  2423. await flushMicrotasks();
  2424. expect(agent.sendConversationCommandV4).toHaveBeenCalledTimes(1);
  2425. });
  2426. it("keeps a running mobile task command when cancel races with drain", async () => {
  2427. const { service } = createService();
  2428. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2429. await service.enqueueTaskCommand({
  2430. workspacePath: "/repo",
  2431. taskId: task.taskId,
  2432. commandId: "queued_running",
  2433. traceId: "input_running",
  2434. queryId: "query_running",
  2435. type: "send_prompt",
  2436. content: "already running",
  2437. });
  2438. await flushMicrotasks();
  2439. const result = await service.cancelTaskCommand({
  2440. workspacePath: "/repo",
  2441. taskId: task.taskId,
  2442. commandId: "queued_running",
  2443. clientMode: "web-remote-replayable",
  2444. });
  2445. expect(result).toEqual(
  2446. expect.objectContaining({
  2447. canceled: false,
  2448. commandId: "queued_running",
  2449. reason: "already_running",
  2450. status: "running",
  2451. }),
  2452. );
  2453. const snapshot = await service.getTaskSnapshot({
  2454. workspacePath: "/repo",
  2455. taskId: task.taskId,
  2456. clientMode: "web-remote-replayable",
  2457. });
  2458. expect(snapshot?.runtime?.pendingCommands).toEqual([
  2459. expect.objectContaining({
  2460. commandId: "queued_running",
  2461. status: "running",
  2462. traceId: "input_running",
  2463. }),
  2464. ]);
  2465. });
  2466. it("keeps mobile clientId on the v4 sendText envelope when draining a host command", async () => {
  2467. const { agent, indexFrameEmitter, service } = createService();
  2468. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2469. await service.sendPrompt({
  2470. taskId: task.taskId,
  2471. traceId: "input_first",
  2472. content: "first",
  2473. });
  2474. await service.enqueueTaskCommand({
  2475. workspacePath: "/repo",
  2476. taskId: task.taskId,
  2477. commandId: "queued_second",
  2478. traceId: "input_second",
  2479. type: "send_prompt",
  2480. content: "second",
  2481. clientId: "mobile-client-7",
  2482. });
  2483. await firePromptCompletedState(indexFrameEmitter, {
  2484. sessionId: task.taskId,
  2485. workspacePath: "/repo",
  2486. });
  2487. await flushMicrotasks();
  2488. expect(agent.sendConversationCommandV4).toHaveBeenLastCalledWith(
  2489. expect.objectContaining({
  2490. envelope: expect.objectContaining({
  2491. commandId: "input_second",
  2492. clientId: "mobile-client-7",
  2493. }),
  2494. }),
  2495. );
  2496. });
  2497. it("marks a drained mobile command failed when the v4 sendText ACK is rejected", async () => {
  2498. const { agent, service } = createService();
  2499. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2500. vi.mocked(agent.sendConversationCommandV4).mockResolvedValueOnce({
  2501. commandId: "input_failed",
  2502. status: "failed",
  2503. reasonCode: "fault.command.executionFailed",
  2504. message: "boom",
  2505. revisionAtDecision: 3,
  2506. });
  2507. await service.enqueueTaskCommand({
  2508. workspacePath: "/repo",
  2509. taskId: task.taskId,
  2510. commandId: "queued_failed",
  2511. traceId: "input_failed",
  2512. type: "send_prompt",
  2513. content: "will fail",
  2514. });
  2515. await flushMicrotasks();
  2516. const snapshot = await service.getTaskSnapshot({
  2517. workspacePath: "/repo",
  2518. taskId: task.taskId,
  2519. clientMode: "web-remote-replayable",
  2520. });
  2521. expect(snapshot?.runtime?.pendingCommands).toEqual([
  2522. expect.objectContaining({
  2523. commandId: "queued_failed",
  2524. status: "failed",
  2525. error: expect.stringContaining("fault.command.executionFailed"),
  2526. }),
  2527. ]);
  2528. });
  2529. it("keeps attachment prompts on the legacy session/send fallback", async () => {
  2530. const { agent, service } = createService();
  2531. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2532. vi.mocked(agent.sendConversationCommandV4).mockClear();
  2533. await service.sendPrompt({
  2534. taskId: task.taskId,
  2535. traceId: "input_attach",
  2536. content: "see image",
  2537. modelSelection: {
  2538. providerId: "test-provider",
  2539. modelId: "test-model",
  2540. options: { reasoningLevel: "high" },
  2541. },
  2542. modelExecution: { selectionScope: "execution", memoryExtraction: "skip" },
  2543. attachments: [
  2544. { kind: "image", filename: "a.png", mimeType: "image/png", dataBase64: "aGk=" },
  2545. ],
  2546. });
  2547. // 附件命令面未建模(v4 attachmentRef 引用模型缺上传面):带附件输入仍走旧 session/send。
  2548. expect(agent.sendConversationCommandV4).not.toHaveBeenCalled();
  2549. expect(agent.sendPrompt).toHaveBeenCalledWith(
  2550. expect.objectContaining({
  2551. inputId: "input_attach",
  2552. modelSelection: {
  2553. providerId: "test-provider",
  2554. modelId: "test-model",
  2555. options: { reasoningLevel: "high" },
  2556. },
  2557. modelExecution: { selectionScope: "execution", memoryExtraction: "skip" },
  2558. attachments: [expect.objectContaining({ filename: "a.png" })],
  2559. }),
  2560. );
  2561. });
  2562. it("requires authoritative identity before stopping a running topic", async () => {
  2563. const { service } = createService();
  2564. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2565. const target = { taskId: task.taskId, workspacePath: "/repo" };
  2566. vi.mocked(readBotGroupRuntimeSnapshot).mockResolvedValueOnce({
  2567. control: { stopState: "idle", activeWorks: [] },
  2568. } as never);
  2569. await expect(service.readBotTopicExecution!(target)).resolves.toBeUndefined();
  2570. vi.mocked(readBotGroupRuntimeSnapshot).mockResolvedValueOnce({
  2571. control: {
  2572. stopState: "stoppable",
  2573. activeWorks: [
  2574. {
  2575. kind: "primaryTurn",
  2576. foregroundExecutionId: "execution",
  2577. sourceCommandId: "input-current",
  2578. },
  2579. ],
  2580. },
  2581. } as never);
  2582. await expect(service.readBotTopicExecution!(target)).resolves.toEqual({
  2583. executionId: "execution",
  2584. sourceCommandId: "input-current",
  2585. });
  2586. vi.mocked(readBotGroupRuntimeSnapshot).mockResolvedValueOnce({
  2587. control: { stopState: "stoppable", activeWorks: [] },
  2588. } as never);
  2589. await expect(service.readBotTopicExecution!(target)).rejects.toThrow("identity is unavailable");
  2590. });
  2591. it("routes topic stop through the same workspace and waits for its execution to end", async () => {
  2592. const { agent, service } = createService();
  2593. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2594. let finish!: () => void;
  2595. vi.mocked(waitBotGroupExecutionEnd).mockImplementationOnce(
  2596. () =>
  2597. new Promise((resolve) => {
  2598. finish = () => resolve({} as never);
  2599. }),
  2600. );
  2601. let completed = false;
  2602. const stopping = service.stopBotTopicExecution!({
  2603. taskId: task.taskId,
  2604. workspacePath: "/repo",
  2605. remoteSessionId: "remote-a",
  2606. executionId: "old",
  2607. }).then(() => {
  2608. completed = true;
  2609. });
  2610. for (let i = 0; i < 8; i++) await Promise.resolve();
  2611. expect(agent.sendConversationCommandV4).toHaveBeenLastCalledWith(
  2612. expect.objectContaining({
  2613. remoteSessionId: "remote-a",
  2614. envelope: expect.objectContaining({
  2615. type: "stop",
  2616. payload: { expectedForegroundExecutionId: "old" },
  2617. }),
  2618. }),
  2619. );
  2620. expect(completed).toBe(false);
  2621. finish();
  2622. await stopping;
  2623. expect(completed).toBe(true);
  2624. });
  2625. it("preserves the observed execution identity in a topic stop", async () => {
  2626. const { agent, service } = createService();
  2627. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2628. await service.stopGeneration({
  2629. taskId: task.taskId,
  2630. expectedForegroundExecutionId: "old-execution",
  2631. });
  2632. expect(agent.sendConversationCommandV4).toHaveBeenLastCalledWith(
  2633. expect.objectContaining({
  2634. envelope: expect.objectContaining({
  2635. type: "stop",
  2636. payload: { expectedForegroundExecutionId: "old-execution" },
  2637. }),
  2638. }),
  2639. );
  2640. });
  2641. it("routes stopGeneration through the v4 stop command", async () => {
  2642. const { agent, service } = createService();
  2643. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2644. await service.stopGeneration({ taskId: task.taskId });
  2645. // M5 ③-4:agentService.stopSession 已删除(v4 stop 命令唯一路径),断言收敛为 v4 面。
  2646. expect(agent.sendConversationCommandV4).toHaveBeenLastCalledWith({
  2647. workspacePath: "/repo",
  2648. workspaceIdentity: undefined,
  2649. envelope: expect.objectContaining({
  2650. type: "stop",
  2651. sessionId: task.taskId,
  2652. payload: {},
  2653. }),
  2654. });
  2655. });
  2656. // M5 ③-3:模式切换(手机远控语义入口 setMode/setConfigOption)收敛 v4 switchCollaborationMode。
  2657. it("routes setMode through the v4 switchCollaborationMode command", async () => {
  2658. const { agent, service } = createService();
  2659. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2660. await service.setMode({ taskId: task.taskId, mode: "plan" });
  2661. expect(agent.setMode).not.toHaveBeenCalled();
  2662. expect(agent.sendConversationCommandV4).toHaveBeenLastCalledWith({
  2663. workspacePath: "/repo",
  2664. workspaceIdentity: undefined,
  2665. envelope: expect.objectContaining({
  2666. type: "switchCollaborationMode",
  2667. sessionId: task.taskId,
  2668. payload: { mode: "plan" },
  2669. }),
  2670. });
  2671. });
  2672. // M5 ③-3:host 无本地 v4 投影,CAS 首发 baseRevision=0 探测,stale 用 revisionAtDecision 收敛。
  2673. it("retries a stale switchCollaborationMode ACK with the server revision", async () => {
  2674. const { agent, service } = createService();
  2675. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2676. vi.mocked(agent.sendConversationCommandV4).mockResolvedValueOnce({
  2677. commandId: "probe",
  2678. status: "stale",
  2679. reasonCode: "proto.staleRevision",
  2680. revisionAtDecision: 7,
  2681. });
  2682. await service.setMode({ taskId: task.taskId, mode: "yolo" });
  2683. const envelopes = vi
  2684. .mocked(agent.sendConversationCommandV4)
  2685. .mock.calls.filter(([params]) => params.envelope.type === "switchCollaborationMode")
  2686. .map(([params]) => params.envelope);
  2687. expect(envelopes).toHaveLength(2);
  2688. expect(envelopes[0]).toMatchObject({ baseRevision: 0 });
  2689. expect(envelopes[1]).toMatchObject({ baseRevision: 7, payload: { mode: "yolo" } });
  2690. });
  2691. // M5 ③-3 残留保真:v4 switchCollaborationMode 值域刻意排除 auto,auto 继续走旧 op。
  2692. it("keeps mode=auto on the legacy session/setMode fallback", async () => {
  2693. const { agent, service } = createService();
  2694. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2695. await service.setMode({ taskId: task.taskId, mode: "auto" });
  2696. expect(agent.setMode).toHaveBeenCalledWith(
  2697. expect.objectContaining({ sessionId: task.taskId, mode: "auto" }),
  2698. );
  2699. expect(
  2700. vi
  2701. .mocked(agent.sendConversationCommandV4)
  2702. .mock.calls.some(([params]) => params.envelope.type === "switchCollaborationMode"),
  2703. ).toBe(false);
  2704. });
  2705. // M5 ③-3:思考深度收敛 v4 switchModelConfig(thought 字段承载,provider/model 取当前选型)。
  2706. it("routes thought level config through v4 switchModelConfig with the current model", async () => {
  2707. const { agent, service } = createService();
  2708. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2709. const configOptions = await service.setConfigOption({
  2710. taskId: task.taskId,
  2711. configId: "thought_level",
  2712. value: "max",
  2713. });
  2714. expect(agent.setThoughtLevel).not.toHaveBeenCalled();
  2715. expect(agent.sendConversationCommandV4).toHaveBeenLastCalledWith({
  2716. workspacePath: "/repo",
  2717. workspaceIdentity: undefined,
  2718. envelope: expect.objectContaining({
  2719. type: "switchModelConfig",
  2720. sessionId: task.taskId,
  2721. payload: { provider: "glm", model: "glm-4.6", thought: "max" },
  2722. }),
  2723. });
  2724. expect(configOptions.some((option) => option.id === "thought_level")).toBe(true);
  2725. });
  2726. // M5 ③-3 评估标注保真:setModel 仍走旧 op(v4 switchModelConfig 无 runtimeModel 解析,
  2727. // 迁移会让手机远控的 custom provider 跨切失效)。
  2728. it("keeps setModel on the legacy session/setModel op", async () => {
  2729. const { agent, service } = createService();
  2730. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2731. await service.setModel({
  2732. taskId: task.taskId,
  2733. modelSelection: { providerId: "glm", modelId: "glm-4.7" },
  2734. });
  2735. expect(agent.setModel).toHaveBeenCalledWith(
  2736. expect.objectContaining({ sessionId: task.taskId }),
  2737. );
  2738. expect(
  2739. vi
  2740. .mocked(agent.sendConversationCommandV4)
  2741. .mock.calls.some(([params]) => params.envelope.type === "switchModelConfig"),
  2742. ).toBe(false);
  2743. });
  2744. it("routes local automation selection through V4 commands without Host runtimeModel", async () => {
  2745. const { agent, service } = createService();
  2746. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2747. await service.setAutomationSessionConfig({
  2748. taskId: task.taskId,
  2749. traceId: "automation-run" as TraceId,
  2750. modelSelection: { providerId: "provider-deepseek", modelId: "deepseek-v4-pro" },
  2751. thoughtLevel: "high",
  2752. mode: "edit",
  2753. });
  2754. expect(agent.setModel).not.toHaveBeenCalled();
  2755. expect(agent.setThoughtLevel).not.toHaveBeenCalled();
  2756. const automationCommands = vi
  2757. .mocked(agent.sendConversationCommandV4)
  2758. .mock.calls.map(([params]) => params.envelope)
  2759. .slice(-3);
  2760. expect(automationCommands).toEqual([
  2761. expect.objectContaining({
  2762. type: "switchModelConfig",
  2763. payload: expect.objectContaining({
  2764. provider: "provider-deepseek",
  2765. model: "deepseek-v4-pro",
  2766. thought: "high",
  2767. }),
  2768. }),
  2769. expect.objectContaining({
  2770. type: "switchModelConfig",
  2771. payload: {
  2772. provider: "provider-deepseek",
  2773. model: "deepseek-v4-pro",
  2774. thought: "high",
  2775. },
  2776. }),
  2777. expect.objectContaining({
  2778. type: "switchCollaborationMode",
  2779. payload: { mode: "edit" },
  2780. }),
  2781. ]);
  2782. });
  2783. it("routes desktop-attached remote automation with ModelSelection only", async () => {
  2784. const { agent, service } = createService();
  2785. const task = await service.createTask({
  2786. workspacePath: "/repo",
  2787. workspaceIdentity: "remote:ssh:dev:/repo",
  2788. provider: "glm",
  2789. });
  2790. await service.setAutomationSessionConfig({
  2791. taskId: task.taskId,
  2792. traceId: "remote-automation-run" as TraceId,
  2793. modelSelection: { providerId: "provider-deepseek", modelId: "deepseek-v4-pro" },
  2794. thoughtLevel: "high",
  2795. mode: "edit",
  2796. });
  2797. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith(
  2798. expect.objectContaining({
  2799. workspaceIdentity: "remote:ssh:dev:/repo",
  2800. envelope: expect.objectContaining({
  2801. type: "switchModelConfig",
  2802. payload: expect.objectContaining({
  2803. provider: "provider-deepseek",
  2804. model: "deepseek-v4-pro",
  2805. thought: "high",
  2806. }),
  2807. }),
  2808. }),
  2809. );
  2810. const modelCommand = vi
  2811. .mocked(agent.sendConversationCommandV4)
  2812. .mock.calls.map(([params]) => params.envelope)
  2813. .find((envelope) => envelope.type === "switchModelConfig");
  2814. expect(modelCommand?.payload).not.toHaveProperty("runtimeModel");
  2815. });
  2816. it("routes respondPermission through v4 resolveInteraction keyed by requestId", async () => {
  2817. const { agent, service } = createService();
  2818. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2819. const submitted = await service.respondPermission({
  2820. taskId: task.taskId,
  2821. requestId: "perm_req_1",
  2822. optionId: "allow_project",
  2823. response: { decision: "allow", reason: "Approved" },
  2824. });
  2825. expect(submitted).toBe(true);
  2826. // M5 ③-4:agentService.respondPermission 已删除(v4 resolveInteraction 唯一路径)。
  2827. expect(agent.sendConversationCommandV4).toHaveBeenLastCalledWith({
  2828. workspacePath: "/repo",
  2829. workspaceIdentity: undefined,
  2830. envelope: expect.objectContaining({
  2831. type: "resolveInteraction",
  2832. sessionId: task.taskId,
  2833. payload: {
  2834. interactionId: "perm_req_1",
  2835. answer: { optionId: "allow_project" },
  2836. },
  2837. }),
  2838. });
  2839. });
  2840. it("routes respondElicitation through v4 resolveInteraction with action/content", async () => {
  2841. const { agent, service } = createService();
  2842. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2843. const received: ZCodeStreamEvent[] = [];
  2844. const disposable = service.onDynamicTaskEvent({
  2845. workspacePath: "/repo",
  2846. taskId: task.taskId,
  2847. deliveryKind: "replayable",
  2848. })((event) => {
  2849. received.push(event);
  2850. });
  2851. try {
  2852. const submitted = await service.respondElicitation({
  2853. taskId: task.taskId,
  2854. requestId: "elicit_req_1",
  2855. action: "accept",
  2856. content: { answers: { "Pick one": "B" } },
  2857. clientMode: "web-remote-replayable",
  2858. });
  2859. expect(submitted).toBe(true);
  2860. expect(agent.sendConversationCommandV4).toHaveBeenLastCalledWith({
  2861. workspacePath: "/repo",
  2862. workspaceIdentity: undefined,
  2863. envelope: expect.objectContaining({
  2864. type: "resolveInteraction",
  2865. sessionId: task.taskId,
  2866. payload: {
  2867. interactionId: "elicit_req_1",
  2868. answer: {
  2869. action: "accept",
  2870. content: { answers: { "Pick one": "B" } },
  2871. },
  2872. },
  2873. }),
  2874. });
  2875. // 语义保真:replayable 应答后 observer 弹窗按 elicitation_response 清理(原
  2876. // respondUserInput 的 web-remote-replayable 分支,现由 adapter 本地补投)。
  2877. expect(received).toContainEqual(
  2878. expect.objectContaining({
  2879. type: "elicitation_response",
  2880. requestId: "elicit_req_1",
  2881. action: "accept",
  2882. }),
  2883. );
  2884. } finally {
  2885. disposable.dispose();
  2886. }
  2887. });
  2888. it("treats a noop resolveInteraction ACK as an idempotent success", async () => {
  2889. const { agent, service } = createService();
  2890. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2891. vi.mocked(agent.sendConversationCommandV4).mockResolvedValueOnce({
  2892. commandId: "any",
  2893. status: "noop",
  2894. reasonCode: "proto.alreadyResolved",
  2895. revisionAtDecision: 9,
  2896. });
  2897. await expect(
  2898. service.respondPermission({
  2899. taskId: task.taskId,
  2900. requestId: "perm_req_late",
  2901. optionId: "deny",
  2902. response: { decision: "deny", reason: "Denied" },
  2903. }),
  2904. ).resolves.toBe(true);
  2905. });
  2906. it("merges live subagent tool projection into terminal ZCode snapshots", async () => {
  2907. const { agent, eventEmitter, service } = createService();
  2908. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  2909. const terminalSnapshot = makeSnapshot({
  2910. sessionId: task.taskId,
  2911. workspacePath: "/repo",
  2912. messages: [
  2913. makeUserMessage({
  2914. sessionId: task.taskId,
  2915. messageId: "msg_user_1",
  2916. text: "加一个地址系统,可以加,可以选",
  2917. }),
  2918. makeAssistantAgentToolMessage({
  2919. sessionId: task.taskId,
  2920. messageId: "msg_assistant_1",
  2921. toolCallId: "call_00_agent",
  2922. }),
  2923. ],
  2924. });
  2925. vi.mocked(agent.resumeSession).mockResolvedValue({
  2926. ...terminalSnapshot,
  2927. session: {
  2928. ...terminalSnapshot.session,
  2929. status: "completed",
  2930. },
  2931. projection: {
  2932. ...terminalSnapshot.projection,
  2933. status: "completed",
  2934. },
  2935. });
  2936. const streamEvents: ZCodeStreamEvent[] = [];
  2937. const disposable = service.onDynamicTaskEvent({
  2938. workspacePath: "/repo",
  2939. taskId: task.taskId,
  2940. })((event) => {
  2941. streamEvents.push(event);
  2942. });
  2943. try {
  2944. const scheduledEvent: ZCodeSessionEvent = {
  2945. eventId: "evt_subagent_tool_scheduled",
  2946. sessionId: task.taskId,
  2947. turnId: "turn_1",
  2948. seq: 1,
  2949. traceId: "trace_subagent_tool",
  2950. timestamp: 60,
  2951. type: "tool.updated",
  2952. payload: {
  2953. kind: "scheduled",
  2954. toolCallId: "tool_subagent_read",
  2955. toolName: "Read",
  2956. input: { file_path: "package.json" },
  2957. parentToolCallId: "call_00_agent",
  2958. source: "subagent",
  2959. agentId: "agent_1",
  2960. agentType: "Explore",
  2961. childSessionId: "sess_subagent_agent_1",
  2962. childToolCallId: "call_child_read",
  2963. },
  2964. };
  2965. const resultEvent: ZCodeSessionEvent = {
  2966. eventId: "evt_subagent_tool_result",
  2967. sessionId: task.taskId,
  2968. turnId: "turn_1",
  2969. seq: 4,
  2970. traceId: "trace_subagent_tool",
  2971. timestamp: 63,
  2972. type: "tool.updated",
  2973. payload: {
  2974. kind: "result",
  2975. toolCallId: "tool_subagent_read",
  2976. parentToolCallId: "call_00_agent",
  2977. source: "subagent",
  2978. agentId: "agent_1",
  2979. agentType: "Explore",
  2980. childSessionId: "sess_subagent_agent_1",
  2981. childToolCallId: "call_child_read",
  2982. result: { content: "read output" },
  2983. duration: 10,
  2984. },
  2985. };
  2986. eventEmitter.fire({ type: "session.event", event: scheduledEvent });
  2987. eventEmitter.fire({
  2988. type: "session.event",
  2989. event: {
  2990. eventId: "evt_subagent_tool_progress",
  2991. sessionId: task.taskId,
  2992. turnId: "turn_1",
  2993. seq: 2,
  2994. traceId: "trace_subagent_tool",
  2995. timestamp: 61,
  2996. type: "tool.updated",
  2997. payload: {
  2998. kind: "started",
  2999. toolCallId: "tool_subagent_read",
  3000. toolName: "Read",
  3001. parentToolCallId: "call_00_agent",
  3002. source: "subagent",
  3003. agentId: "agent_1",
  3004. },
  3005. },
  3006. });
  3007. eventEmitter.fire({
  3008. type: "session.event",
  3009. event: {
  3010. eventId: "evt_parent_turn_completed",
  3011. sessionId: task.taskId,
  3012. turnId: "turn_1",
  3013. seq: 3,
  3014. traceId: "trace_subagent_tool",
  3015. timestamp: 62,
  3016. type: "turn.completed",
  3017. payload: {
  3018. inputId: "input_parent",
  3019. resultType: "success",
  3020. },
  3021. },
  3022. });
  3023. eventEmitter.fire({ type: "session.event", event: resultEvent });
  3024. expect(streamEvents).toContainEqual(
  3025. expect.objectContaining({
  3026. type: "tool_call_update",
  3027. toolId: "tool_subagent_read",
  3028. toolName: "Read",
  3029. status: "in_progress",
  3030. input: { file_path: "package.json" },
  3031. }),
  3032. );
  3033. expect(streamEvents).toContainEqual(
  3034. expect.objectContaining({
  3035. type: "tool_call_update",
  3036. toolId: "tool_subagent_read",
  3037. parentToolUseId: "call_00_agent",
  3038. toolName: "Read",
  3039. status: "completed",
  3040. input: { file_path: "package.json" },
  3041. }),
  3042. );
  3043. const snapshot = await service.getTaskSnapshot({
  3044. workspacePath: "/repo",
  3045. taskId: task.taskId,
  3046. });
  3047. const tools = snapshot?.messages[1]?.tools ?? [];
  3048. const childTool = tools.find(
  3049. (tool) =>
  3050. (tool.raw as { toolCallId?: string } | undefined)?.toolCallId === "tool_subagent_read",
  3051. );
  3052. expect(tools).toHaveLength(2);
  3053. expect(childTool?.output).toBe("read output");
  3054. expect((childTool?.raw as { parentToolCallId?: string } | undefined)?.parentToolCallId).toBe(
  3055. "call_00_agent",
  3056. );
  3057. } finally {
  3058. disposable.dispose();
  3059. }
  3060. });
  3061. it("attaches hidden task notification metadata to background Agent tools in restored snapshots", async () => {
  3062. const { agent, service } = createService();
  3063. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  3064. const restored = makeSnapshot({
  3065. sessionId: task.taskId,
  3066. workspacePath: "/repo",
  3067. messages: [
  3068. makeUserMessage({
  3069. sessionId: task.taskId,
  3070. messageId: "msg_user_1",
  3071. text: "启动后台 Agent",
  3072. }),
  3073. {
  3074. info: {
  3075. messageId: "msg_assistant_agent",
  3076. sessionId: task.taskId,
  3077. role: "assistant",
  3078. time: { created: 40, completed: 50 },
  3079. agent: "glm",
  3080. model: { providerId: "glm", modelId: "glm-4.6" },
  3081. },
  3082. parts: [
  3083. {
  3084. partId: "part_agent_tool",
  3085. sessionId: task.taskId,
  3086. messageId: "msg_assistant_agent",
  3087. type: "tool",
  3088. callId: "toolu_background_agent",
  3089. tool: "Agent",
  3090. state: {
  3091. status: "completed",
  3092. input: {
  3093. prompt: "Explore project structure",
  3094. run_in_background: true,
  3095. },
  3096. output:
  3097. "Async agent launched successfully.\noutput_file: /tmp/background-agent.output",
  3098. title: "Agent",
  3099. metadata: {},
  3100. startedAt: 41,
  3101. completedAt: 49,
  3102. },
  3103. },
  3104. ],
  3105. } satisfies ZCodeMessageWithParts,
  3106. makeUserMessage({
  3107. sessionId: task.taskId,
  3108. messageId: "msg_task_notification",
  3109. text: [
  3110. "<task-notification>",
  3111. "<task-id>agent_1</task-id>",
  3112. "<tool-use-id>toolu_background_agent</tool-use-id>",
  3113. "<output-file>/tmp/background-agent.output</output-file>",
  3114. "<status>completed</status>",
  3115. "<result>Background Agent restored result</result>",
  3116. "</task-notification>",
  3117. ].join("\n"),
  3118. parts: [
  3119. {
  3120. partId: "part_task_notification",
  3121. sessionId: task.taskId,
  3122. messageId: "msg_task_notification",
  3123. type: "text",
  3124. synthetic: true,
  3125. metadata: { source: "background_task" },
  3126. text: [
  3127. "<task-notification>",
  3128. "<task-id>agent_1</task-id>",
  3129. "<tool-use-id>toolu_background_agent</tool-use-id>",
  3130. "<output-file>/tmp/background-agent.output</output-file>",
  3131. "<status>completed</status>",
  3132. "<result>Background Agent restored result</result>",
  3133. "</task-notification>",
  3134. ].join("\n"),
  3135. },
  3136. ],
  3137. }),
  3138. ],
  3139. });
  3140. vi.mocked(agent.resumeSession).mockResolvedValueOnce(restored);
  3141. const snapshot = await service.getTaskSnapshot({
  3142. workspacePath: "/repo",
  3143. taskId: task.taskId,
  3144. });
  3145. expect(snapshot?.messages).toHaveLength(2);
  3146. expect(snapshot?.messages[1]?.tools?.[0]?.raw).toMatchObject({
  3147. _meta: {
  3148. zcode: {
  3149. taskNotification: {
  3150. outputFile: "/tmp/background-agent.output",
  3151. result: "Background Agent restored result",
  3152. status: "completed",
  3153. taskId: "agent_1",
  3154. },
  3155. },
  3156. },
  3157. });
  3158. });
  3159. it.each([
  3160. {
  3161. expectedError: BACKGROUND_AGENT_PROVIDER_ERROR,
  3162. expectedStatus: "failed" as const,
  3163. notificationStatus: "failed",
  3164. },
  3165. {
  3166. expectedError: undefined,
  3167. expectedStatus: "completed" as const,
  3168. notificationStatus: "stopped",
  3169. },
  3170. ])(
  3171. "restores a $notificationStatus background Agent notification without changing unrelated launch semantics",
  3172. async ({ expectedError, expectedStatus, notificationStatus }) => {
  3173. const { agent, service } = createService();
  3174. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  3175. const notificationSummary = `Agent general-purpose task "Review" ${notificationStatus}.`;
  3176. const notificationText = [
  3177. "<task-notification>",
  3178. "<task-id>agent_failed</task-id>",
  3179. "<tool-use-id>toolu_background_agent_failed</tool-use-id>",
  3180. "<output-file>/tmp/background-agent-failed.output</output-file>",
  3181. `<status>${notificationStatus}</status>`,
  3182. `<summary>${notificationSummary.replaceAll('"', "&quot;")}</summary>`,
  3183. ...(expectedError ? [`<error>${expectedError}</error>`] : []),
  3184. "</task-notification>",
  3185. ].join("\n");
  3186. const restored = makeSnapshot({
  3187. sessionId: task.taskId,
  3188. workspacePath: "/repo",
  3189. messages: [
  3190. makeUserMessage({
  3191. sessionId: task.taskId,
  3192. messageId: "msg_user_failed",
  3193. text: "启动会失败的后台 Agent",
  3194. }),
  3195. {
  3196. info: {
  3197. messageId: "msg_assistant_failed_agent",
  3198. sessionId: task.taskId,
  3199. role: "assistant",
  3200. time: { created: 40, completed: 50 },
  3201. agent: "glm",
  3202. model: { providerId: "glm", modelId: "glm-4.6" },
  3203. },
  3204. parts: [
  3205. {
  3206. partId: "part_failed_agent_tool",
  3207. sessionId: task.taskId,
  3208. messageId: "msg_assistant_failed_agent",
  3209. type: "tool",
  3210. callId: "toolu_background_agent_failed",
  3211. tool: "Agent",
  3212. state: {
  3213. status: "completed",
  3214. input: {
  3215. prompt: "Review the workspace",
  3216. run_in_background: true,
  3217. },
  3218. output:
  3219. "Async agent launched successfully.\noutput_file: /tmp/background-agent-failed.output",
  3220. title: "Agent",
  3221. metadata: {},
  3222. startedAt: 41,
  3223. completedAt: 49,
  3224. },
  3225. },
  3226. ],
  3227. } satisfies ZCodeMessageWithParts,
  3228. makeUserMessage({
  3229. sessionId: task.taskId,
  3230. messageId: "msg_failed_task_notification",
  3231. text: notificationText,
  3232. parts: [
  3233. {
  3234. partId: "part_failed_task_notification",
  3235. sessionId: task.taskId,
  3236. messageId: "msg_failed_task_notification",
  3237. type: "text",
  3238. synthetic: true,
  3239. metadata: { source: "background_task" },
  3240. text: notificationText,
  3241. },
  3242. ],
  3243. }),
  3244. ],
  3245. });
  3246. vi.mocked(agent.resumeSession).mockResolvedValueOnce(restored);
  3247. const snapshot = await service.getTaskSnapshot({
  3248. workspacePath: "/repo",
  3249. taskId: task.taskId,
  3250. });
  3251. const restoredTool = snapshot?.messages[1]?.tools?.[0];
  3252. expect(restoredTool).toMatchObject({
  3253. status: expectedStatus,
  3254. raw: {
  3255. _meta: {
  3256. zcode: {
  3257. taskNotification: {
  3258. status: notificationStatus,
  3259. summary: notificationSummary,
  3260. taskId: "agent_failed",
  3261. },
  3262. },
  3263. },
  3264. },
  3265. });
  3266. expect(restoredTool?.error).toBe(expectedError);
  3267. },
  3268. );
  3269. it("projects live task notification turns back onto matching background Agent tools", async () => {
  3270. const { eventEmitter, service } = createService();
  3271. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  3272. const streamEvents: ZCodeStreamEvent[] = [];
  3273. const disposable = service.onDynamicTaskEvent({
  3274. workspacePath: "/repo",
  3275. taskId: task.taskId,
  3276. })((event) => {
  3277. streamEvents.push(event);
  3278. });
  3279. try {
  3280. eventEmitter.fire({
  3281. type: "session.event",
  3282. event: {
  3283. eventId: "evt_task_notification_started",
  3284. sessionId: task.taskId,
  3285. turnId: "turn_task_notification",
  3286. seq: 1,
  3287. traceId: "trace_task_notification",
  3288. timestamp: 70,
  3289. type: "turn.started",
  3290. payload: {
  3291. input: [
  3292. "<task-notification>",
  3293. "<task-id>agent_1</task-id>",
  3294. "<tool-use-id>toolu_background_agent</tool-use-id>",
  3295. "<output-file>/tmp/background-agent.output</output-file>",
  3296. "<status>completed</status>",
  3297. "<summary>Agent general-purpose task &quot;Review&quot; completed.</summary>",
  3298. "<result>Background Agent live result</result>",
  3299. "</task-notification>",
  3300. ].join("\n"),
  3301. inputSource: "task-notification",
  3302. inputVisibility: "model-only",
  3303. },
  3304. },
  3305. });
  3306. expect(streamEvents).toContainEqual(
  3307. expect.objectContaining({
  3308. type: "tool_call_update",
  3309. taskId: task.taskId,
  3310. toolId: "toolu_background_agent",
  3311. status: "completed",
  3312. content: "Background Agent live result",
  3313. raw: expect.objectContaining({
  3314. _meta: expect.objectContaining({
  3315. zcode: expect.objectContaining({
  3316. taskNotification: {
  3317. outputFile: "/tmp/background-agent.output",
  3318. result: "Background Agent live result",
  3319. status: "completed",
  3320. summary: 'Agent general-purpose task "Review" completed.',
  3321. taskId: "agent_1",
  3322. },
  3323. }),
  3324. }),
  3325. toolCallId: "toolu_background_agent",
  3326. }),
  3327. }),
  3328. );
  3329. } finally {
  3330. disposable.dispose();
  3331. }
  3332. });
  3333. it("projects failed live task notifications with the provider error on matching Agent tools", async () => {
  3334. const { eventEmitter, service } = createService();
  3335. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  3336. const streamEvents: ZCodeStreamEvent[] = [];
  3337. const disposable = service.onDynamicTaskEvent({
  3338. workspacePath: "/repo",
  3339. taskId: task.taskId,
  3340. })((event) => {
  3341. streamEvents.push(event);
  3342. });
  3343. try {
  3344. eventEmitter.fire({
  3345. type: "session.event",
  3346. event: {
  3347. eventId: "evt_failed_task_notification_started",
  3348. sessionId: task.taskId,
  3349. turnId: "turn_failed_task_notification",
  3350. seq: 1,
  3351. traceId: "trace_failed_task_notification",
  3352. timestamp: 80,
  3353. type: "turn.started",
  3354. payload: {
  3355. input: [
  3356. "<task-notification>",
  3357. "<task-id>agent_failed</task-id>",
  3358. "<tool-use-id>toolu_background_agent_failed</tool-use-id>",
  3359. "<output-file>/tmp/background-agent-failed.output</output-file>",
  3360. "<status>failed</status>",
  3361. `<summary>${BACKGROUND_AGENT_FAILED_SUMMARY.replaceAll('"', "&quot;")}</summary>`,
  3362. `<error>${BACKGROUND_AGENT_PROVIDER_ERROR}</error>`,
  3363. "</task-notification>",
  3364. ].join("\n"),
  3365. inputSource: "task-notification",
  3366. inputVisibility: "model-only",
  3367. },
  3368. },
  3369. });
  3370. } finally {
  3371. disposable.dispose();
  3372. }
  3373. const failedUpdate = streamEvents.find(
  3374. (event): event is Extract<ZCodeStreamEvent, { type: "tool_call_update" }> =>
  3375. event.type === "tool_call_update" && event.toolId === "toolu_background_agent_failed",
  3376. );
  3377. expect(failedUpdate).toMatchObject({
  3378. type: "tool_call_update",
  3379. taskId: task.taskId,
  3380. toolId: "toolu_background_agent_failed",
  3381. status: "failed",
  3382. error: BACKGROUND_AGENT_PROVIDER_ERROR,
  3383. raw: {
  3384. _meta: {
  3385. zcode: {
  3386. taskNotification: {
  3387. error: BACKGROUND_AGENT_PROVIDER_ERROR,
  3388. status: "failed",
  3389. summary: BACKGROUND_AGENT_FAILED_SUMMARY,
  3390. taskId: "agent_failed",
  3391. },
  3392. },
  3393. },
  3394. },
  3395. });
  3396. });
  3397. it("merges live background job updates with restored replayable snapshot jobs", async () => {
  3398. const { agent, eventEmitter, service } = createService();
  3399. const workspacePath = "/repo";
  3400. const workspaceIdentity = "remote:ssh:dev:/repo";
  3401. const task = await service.createTask({
  3402. workspacePath,
  3403. workspaceIdentity,
  3404. provider: "glm",
  3405. });
  3406. const restored = makeSnapshot({
  3407. sessionId: task.taskId,
  3408. workspacePath,
  3409. workspaceIdentity,
  3410. backgroundJobs: [
  3411. {
  3412. type: "background_bash",
  3413. taskId: "bash_a",
  3414. command: "sleep 1",
  3415. status: "running",
  3416. background: true,
  3417. },
  3418. {
  3419. type: "background_bash",
  3420. taskId: "bash_b",
  3421. command: "sleep 2",
  3422. status: "running",
  3423. background: true,
  3424. },
  3425. ],
  3426. });
  3427. vi.mocked(agent.resumeSession).mockResolvedValueOnce(restored);
  3428. const snapshot = await service.getTaskSnapshot({
  3429. workspacePath,
  3430. workspaceIdentity,
  3431. taskId: task.taskId,
  3432. });
  3433. expect(snapshot?.runtime?.backgroundBashJobs?.map((job) => job.jobId)).toEqual([
  3434. "bash_a",
  3435. "bash_b",
  3436. ]);
  3437. const streamEvents: ZCodeStreamEvent[] = [];
  3438. const disposable = service.onDynamicTaskEvent({
  3439. workspacePath,
  3440. workspaceIdentity,
  3441. taskId: task.taskId,
  3442. deliveryKind: "replayable",
  3443. })((event) => {
  3444. streamEvents.push(event);
  3445. });
  3446. try {
  3447. eventEmitter.fire({
  3448. type: "session.event",
  3449. event: {
  3450. eventId: "evt_background_job_update",
  3451. sessionId: task.taskId,
  3452. seq: 1,
  3453. timestamp: 70,
  3454. type: "session.updated",
  3455. payload: {
  3456. type: "background_bash",
  3457. taskId: "bash_a",
  3458. command: "sleep 1",
  3459. status: "completed",
  3460. background: true,
  3461. },
  3462. },
  3463. });
  3464. const backgroundUpdate = streamEvents.findLast(
  3465. (event): event is Extract<ZCodeStreamEvent, { type: "background_bash_jobs_update" }> =>
  3466. event.type === "background_bash_jobs_update",
  3467. );
  3468. expect(backgroundUpdate?.jobs.map((job) => [job.jobId, job.status])).toEqual([
  3469. ["bash_a", "completed"],
  3470. ["bash_b", "running"],
  3471. ]);
  3472. } finally {
  3473. disposable.dispose();
  3474. }
  3475. });
  3476. it("filters non-glm legacy task rows in sqlite-backed lists", async () => {
  3477. const { service, taskIndexRepo } = createService();
  3478. await seedIndexedTask(taskIndexRepo, { taskId: "glm_active", provider: "glm" });
  3479. await seedIndexedTask(taskIndexRepo, { taskId: "claude_active", provider: "claude" });
  3480. await seedIndexedTask(taskIndexRepo, {
  3481. taskId: "claude_imported",
  3482. provider: "claude",
  3483. migrationSource: "claudeCode",
  3484. });
  3485. await seedIndexedTask(taskIndexRepo, {
  3486. taskId: "glm_pinned",
  3487. provider: "glm",
  3488. pinned: true,
  3489. });
  3490. await seedIndexedTask(taskIndexRepo, {
  3491. taskId: "claude_pinned",
  3492. provider: "claude",
  3493. pinned: true,
  3494. });
  3495. await seedIndexedTask(taskIndexRepo, {
  3496. taskId: "claude_imported_pinned",
  3497. provider: "claude",
  3498. pinned: true,
  3499. migrationSource: "claudeCode",
  3500. });
  3501. const active = await service.listTasks({ workspacePath: "/repo" });
  3502. const pinned = await service.listPinnedTasks({ workspacePath: "/repo" });
  3503. const pinnedIds = await service.listPinnedTaskIds();
  3504. const taskList = await service.listTaskList({
  3505. kind: "active",
  3506. workspaceScopes: [{ workspacePath: "/repo" }],
  3507. sortBy: "updated",
  3508. });
  3509. // 历史 provider 仍按兼容列表 API 的过滤约定读取。
  3510. expect(active.map((task) => task.taskId)).toEqual(["glm_active"]);
  3511. expect(pinned.map((task) => task.taskId)).toEqual(["glm_pinned"]);
  3512. expect(pinnedIds).toEqual(["glm_pinned"]);
  3513. expect(taskList.items.map((task) => task.taskId)).toEqual(["glm_active"]);
  3514. expect(taskList.total).toBe(1);
  3515. // 项目树曾绕过原列表的 provider 边界,导致能展示却无法经 Controller 操作。
  3516. const tree = (await taskIndexRepo.getProjectRepository()).readTree();
  3517. expect(tree.tasks.map((task) => task.taskId).sort()).toEqual(["glm_active", "glm_pinned"]);
  3518. expect(tree.tasks.filter((task) => task.pinned).map((task) => task.taskId)).toEqual([
  3519. "glm_pinned",
  3520. ]);
  3521. });
  3522. it("does not include zero ZCode Protocol context usage in task snapshots", async () => {
  3523. const { service } = createService();
  3524. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  3525. const snapshot = await service.getTaskSnapshot({
  3526. workspacePath: "/repo",
  3527. taskId: task.taskId,
  3528. });
  3529. expect(snapshot?.runtime?.contextUsage).toBeUndefined();
  3530. });
  3531. it("uses runtime context usage when restored projection has no usage yet", async () => {
  3532. const { agent, service } = createService();
  3533. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  3534. const restored = makeSnapshot({
  3535. sessionId: task.taskId,
  3536. workspacePath: "/repo",
  3537. });
  3538. vi.mocked(agent.resumeSession).mockResolvedValueOnce({
  3539. ...restored,
  3540. projection: {
  3541. ...restored.projection,
  3542. contextUsed: 0,
  3543. },
  3544. runtime: {
  3545. ...restored.runtime,
  3546. contextUsage: {
  3547. used: 12345,
  3548. size: 128000,
  3549. cost: null,
  3550. },
  3551. },
  3552. });
  3553. const snapshot = await service.getTaskSnapshot({
  3554. workspacePath: "/repo",
  3555. taskId: task.taskId,
  3556. });
  3557. expect(snapshot?.runtime?.contextUsage).toEqual({
  3558. used: 12345,
  3559. size: 128000,
  3560. cost: null,
  3561. });
  3562. });
  3563. it("prefers structured projection error code in restored task snapshots", async () => {
  3564. const { agent, service } = createService();
  3565. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  3566. const restored = makeSnapshot({
  3567. sessionId: task.taskId,
  3568. workspacePath: "/repo",
  3569. });
  3570. vi.mocked(agent.resumeSession).mockResolvedValueOnce({
  3571. ...restored,
  3572. session: {
  3573. ...restored.session,
  3574. status: "error",
  3575. },
  3576. projection: {
  3577. ...restored.projection,
  3578. status: "error",
  3579. lastError: {
  3580. type: "MODEL_ERROR",
  3581. code: "provider_not_found",
  3582. message: "Model provider is not configured: stale-provider",
  3583. detail: "stale-provider/gpt-5.5",
  3584. },
  3585. },
  3586. });
  3587. const snapshot = await service.getTaskSnapshot({
  3588. workspacePath: "/repo",
  3589. taskId: task.taskId,
  3590. });
  3591. expect(snapshot?.meta.lastError).toEqual({
  3592. code: "provider_not_found",
  3593. detail: "stale-provider/gpt-5.5",
  3594. message: "Model provider is not configured: stale-provider",
  3595. });
  3596. });
  3597. it("restores protocol user file parts as task message attachments", async () => {
  3598. const { agent, service } = createService();
  3599. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  3600. const imageBase64 = "QUJD";
  3601. const videoBase64 = "REVG";
  3602. vi.mocked(agent.resumeSession).mockResolvedValueOnce(
  3603. makeSnapshot({
  3604. sessionId: task.taskId,
  3605. workspacePath: "/repo",
  3606. messages: [
  3607. makeUserMessage({
  3608. sessionId: task.taskId,
  3609. messageId: "msg_with_attachments",
  3610. text: "inspect attachments",
  3611. parts: [
  3612. {
  3613. partId: "msg_with_attachments_text",
  3614. sessionId: task.taskId,
  3615. messageId: "msg_with_attachments",
  3616. type: "text",
  3617. text: "inspect attachments",
  3618. },
  3619. {
  3620. partId: "msg_with_attachments_file",
  3621. sessionId: task.taskId,
  3622. messageId: "msg_with_attachments",
  3623. type: "file",
  3624. mime: "text/plain",
  3625. filename: "notes.txt",
  3626. url: "/repo/notes.txt",
  3627. metadata: {
  3628. originalUrl: "/repo/notes.txt",
  3629. preview: {
  3630. text: "hello world",
  3631. truncated: false,
  3632. },
  3633. sizeBytes: 11,
  3634. storageKind: "inline",
  3635. },
  3636. },
  3637. {
  3638. partId: "msg_with_attachments_image",
  3639. sessionId: task.taskId,
  3640. messageId: "msg_with_attachments",
  3641. type: "file",
  3642. mime: "image/png",
  3643. filename: "diagram.png",
  3644. url: `data:image/png;base64,${imageBase64}`,
  3645. metadata: {
  3646. originalUrl: "/repo/diagram.png",
  3647. sizeBytes: 3,
  3648. storageKind: "inline",
  3649. },
  3650. },
  3651. {
  3652. partId: "msg_with_attachments_video",
  3653. sessionId: task.taskId,
  3654. messageId: "msg_with_attachments",
  3655. type: "file",
  3656. mime: "video/mp4",
  3657. filename: "demo.mp4",
  3658. url: `data:video/mp4;base64,${videoBase64}`,
  3659. metadata: {
  3660. originalUrl: "/repo/demo.mp4",
  3661. sizeBytes: 3,
  3662. storageKind: "inline",
  3663. },
  3664. },
  3665. ],
  3666. }),
  3667. ],
  3668. }),
  3669. );
  3670. const snapshot = await service.getTaskSnapshot({
  3671. workspacePath: "/repo",
  3672. taskId: task.taskId,
  3673. });
  3674. expect(snapshot?.messages[0]).toMatchObject({
  3675. role: "user",
  3676. content: "inspect attachments",
  3677. attachments: [
  3678. {
  3679. kind: "file",
  3680. filename: "notes.txt",
  3681. mimeType: "text/plain",
  3682. sizeBytes: 11,
  3683. localPath: "/repo/notes.txt",
  3684. },
  3685. {
  3686. kind: "image",
  3687. filename: "diagram.png",
  3688. mimeType: "image/png",
  3689. sizeBytes: 3,
  3690. dataBase64: imageBase64,
  3691. localPath: "/repo/diagram.png",
  3692. },
  3693. {
  3694. kind: "video",
  3695. filename: "demo.mp4",
  3696. mimeType: "video/mp4",
  3697. sizeBytes: 3,
  3698. dataBase64: videoBase64,
  3699. localPath: "/repo/demo.mp4",
  3700. },
  3701. ],
  3702. });
  3703. });
  3704. it("backfills indexed model hint for web remote replayable snapshot resume", async () => {
  3705. const { agent, service, taskIndexRepo } = createService();
  3706. const taskId = "remote_deepseek_task";
  3707. const workspacePath = "/repo";
  3708. await seedIndexedTask(taskIndexRepo, {
  3709. taskId,
  3710. workspacePath,
  3711. provider: "glm",
  3712. model: "default-deepseek/deepseek-v4-flash",
  3713. });
  3714. vi.mocked(agent.resumeSession).mockResolvedValueOnce(
  3715. makeSnapshot({
  3716. sessionId: taskId,
  3717. workspacePath,
  3718. }),
  3719. );
  3720. await service.getTaskSnapshot({
  3721. workspacePath,
  3722. taskId,
  3723. clientMode: "web-remote-replayable",
  3724. });
  3725. expect(agent.resumeSession).toHaveBeenCalledWith(
  3726. expect.objectContaining({
  3727. workspacePath,
  3728. workspaceIdentity: undefined,
  3729. sessionId: taskId,
  3730. model: {
  3731. providerId: "default-deepseek",
  3732. modelId: "deepseek-v4-flash",
  3733. },
  3734. }),
  3735. );
  3736. });
  3737. it("does not backfill indexed model hint for desktop continuous snapshot resume", async () => {
  3738. const { agent, service, taskIndexRepo } = createService();
  3739. const taskId = "desktop_deepseek_task";
  3740. const workspacePath = "/repo";
  3741. await seedIndexedTask(taskIndexRepo, {
  3742. taskId,
  3743. workspacePath,
  3744. provider: "glm",
  3745. model: "default-deepseek/deepseek-v4-flash",
  3746. });
  3747. vi.mocked(agent.resumeSession).mockResolvedValueOnce(
  3748. makeSnapshot({
  3749. sessionId: taskId,
  3750. workspacePath,
  3751. }),
  3752. );
  3753. await service.getTaskSnapshot({
  3754. workspacePath,
  3755. taskId,
  3756. clientMode: "desktop-continuous",
  3757. });
  3758. expect(vi.mocked(agent.resumeSession).mock.calls.at(-1)?.[0]?.model).toBeUndefined();
  3759. });
  3760. it("backfills indexed model hint when resumeTask omits model", async () => {
  3761. const { agent, service, taskIndexRepo } = createService();
  3762. const taskId = "resume_deepseek_task";
  3763. const workspacePath = "/repo";
  3764. await seedIndexedTask(taskIndexRepo, {
  3765. taskId,
  3766. workspacePath,
  3767. provider: "glm",
  3768. model: "default-deepseek/deepseek-v4-flash",
  3769. });
  3770. vi.mocked(agent.resumeSession).mockResolvedValueOnce(
  3771. makeSnapshot({
  3772. sessionId: taskId,
  3773. workspacePath,
  3774. }),
  3775. );
  3776. await service.resumeTask({
  3777. workspacePath,
  3778. taskId,
  3779. });
  3780. expect(agent.resumeSession).toHaveBeenCalledWith(
  3781. expect.objectContaining({
  3782. workspacePath,
  3783. workspaceIdentity: undefined,
  3784. sessionId: taskId,
  3785. model: {
  3786. providerId: "default-deepseek",
  3787. modelId: "deepseek-v4-flash",
  3788. },
  3789. }),
  3790. );
  3791. });
  3792. it("stamps offPeakTaskId on normal snapshot resume (D48)", async () => {
  3793. // SG-01:legacy 分支已补写闲时标记,正常 snapshot 续跑路径必须同语义,
  3794. // 否则 pre-D48 会话被闲时续跑后月亮标识与系统分组归属不会出现。
  3795. const { agent, service, taskIndexRepo } = createService();
  3796. const taskId = "resume_offpeak_stamp_task";
  3797. const workspacePath = "/repo";
  3798. await seedIndexedTask(taskIndexRepo, { taskId, workspacePath, provider: "glm" });
  3799. vi.mocked(agent.resumeSession).mockResolvedValueOnce(
  3800. makeSnapshot({
  3801. sessionId: taskId,
  3802. workspacePath,
  3803. }),
  3804. );
  3805. const meta = await service.resumeTask({
  3806. workspacePath,
  3807. taskId,
  3808. offPeakTaskId: "offpeak-resume-stamp",
  3809. });
  3810. expect(meta.offPeakTaskId).toBe("offpeak-resume-stamp");
  3811. const indexed = await taskIndexRepo.getTaskMeta({ workspacePath, taskId });
  3812. expect(indexed?.offPeakTaskId).toBe("offpeak-resume-stamp");
  3813. });
  3814. it("backfills indexed thought level when resumeTask omits thought level", async () => {
  3815. const { agent, service, taskIndexRepo } = createService();
  3816. const taskId = "resume_glm52_task";
  3817. const workspacePath = "/repo";
  3818. await seedIndexedTask(taskIndexRepo, {
  3819. taskId,
  3820. workspacePath,
  3821. provider: "glm",
  3822. model: "bigmodel-api/GLM-5.2",
  3823. thoughtLevel: "high",
  3824. });
  3825. vi.mocked(agent.resumeSession).mockResolvedValueOnce(
  3826. makeSnapshot({
  3827. sessionId: taskId,
  3828. workspacePath,
  3829. }),
  3830. );
  3831. await service.resumeTask({
  3832. workspacePath,
  3833. taskId,
  3834. });
  3835. expect(agent.resumeSession).toHaveBeenCalledWith(
  3836. expect.objectContaining({
  3837. workspacePath,
  3838. workspaceIdentity: undefined,
  3839. sessionId: taskId,
  3840. model: {
  3841. providerId: "bigmodel-api",
  3842. modelId: "GLM-5.2",
  3843. },
  3844. thoughtLevel: "high",
  3845. }),
  3846. );
  3847. });
  3848. it("backfills indexed thought level for web replayable snapshot resume", async () => {
  3849. const { agent, service, taskIndexRepo } = createService();
  3850. const taskId = "replayable_glm52_task";
  3851. const workspacePath = "/repo";
  3852. await seedIndexedTask(taskIndexRepo, {
  3853. taskId,
  3854. workspacePath,
  3855. provider: "glm",
  3856. model: "bigmodel-api/GLM-5.2",
  3857. thoughtLevel: "high",
  3858. });
  3859. vi.mocked(agent.resumeSession).mockResolvedValueOnce(
  3860. makeSnapshot({
  3861. sessionId: taskId,
  3862. workspacePath,
  3863. }),
  3864. );
  3865. await service.getTaskSnapshot({
  3866. workspacePath,
  3867. taskId,
  3868. clientMode: "web-remote-replayable",
  3869. });
  3870. expect(agent.resumeSession).toHaveBeenCalledWith(
  3871. expect.objectContaining({
  3872. workspacePath,
  3873. workspaceIdentity: undefined,
  3874. sessionId: taskId,
  3875. model: {
  3876. providerId: "bigmodel-api",
  3877. modelId: "GLM-5.2",
  3878. },
  3879. thoughtLevel: "high",
  3880. }),
  3881. );
  3882. });
  3883. it("skips indexed model backfill for web replayable ui-resolved snapshot restore", async () => {
  3884. const { agent, service, taskIndexRepo } = createService();
  3885. const taskId = "replayable_readonly_unavailable_model";
  3886. const workspacePath = "/repo";
  3887. await seedIndexedTask(taskIndexRepo, {
  3888. taskId,
  3889. workspacePath,
  3890. provider: "glm",
  3891. model: "account:bigmodel-individual-coding-plan/GLM-5.2",
  3892. thoughtLevel: "max",
  3893. });
  3894. vi.mocked(agent.resumeSession).mockResolvedValueOnce(
  3895. makeSnapshot({
  3896. sessionId: taskId,
  3897. workspacePath,
  3898. }),
  3899. );
  3900. await service.getTaskSnapshot({
  3901. workspacePath,
  3902. taskId,
  3903. clientMode: "web-remote-replayable",
  3904. resumeModelPolicy: "ui-resolved-only",
  3905. } as Parameters<typeof service.getTaskSnapshot>[0]);
  3906. const resumeParams = vi.mocked(agent.resumeSession).mock.calls[0]?.[0];
  3907. expect(resumeParams).toMatchObject({
  3908. workspacePath,
  3909. workspaceIdentity: undefined,
  3910. sessionId: taskId,
  3911. model: undefined,
  3912. });
  3913. expect(resumeParams?.thoughtLevel).toBeUndefined();
  3914. });
  3915. it("marks idle protocol snapshots with completed assistant turns as completed tasks", async () => {
  3916. const { agent, service } = createService();
  3917. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  3918. const restored = makeSnapshot({
  3919. sessionId: task.taskId,
  3920. workspacePath: "/repo",
  3921. messages: [
  3922. makeUserMessage({
  3923. sessionId: task.taskId,
  3924. messageId: "msg_user_done",
  3925. text: "继续执行",
  3926. }),
  3927. makeAssistantAgentToolMessage({
  3928. sessionId: task.taskId,
  3929. messageId: "msg_assistant_done",
  3930. toolCallId: "tool_done",
  3931. }),
  3932. ],
  3933. });
  3934. vi.mocked(agent.resumeSession).mockResolvedValueOnce({
  3935. ...restored,
  3936. session: {
  3937. ...restored.session,
  3938. status: "idle",
  3939. },
  3940. projection: {
  3941. ...restored.projection,
  3942. status: "idle",
  3943. pendingPermissions: [],
  3944. activeToolCalls: [],
  3945. },
  3946. runtime: {
  3947. ...restored.runtime,
  3948. pendingRequestIds: [],
  3949. },
  3950. });
  3951. const snapshot = await service.getTaskSnapshot({
  3952. workspacePath: "/repo",
  3953. taskId: task.taskId,
  3954. });
  3955. expect(snapshot?.meta.status).toBe("completed");
  3956. });
  3957. it("marks protocol task snapshots when messageLimit trims older history", async () => {
  3958. const { agent, service } = createService();
  3959. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  3960. vi.mocked(agent.resumeSession).mockResolvedValueOnce(
  3961. makeSnapshot({
  3962. sessionId: task.taskId,
  3963. workspacePath: "/repo",
  3964. messages: [
  3965. makeUserMessage({
  3966. sessionId: task.taskId,
  3967. messageId: "message_1",
  3968. text: "message 1",
  3969. }),
  3970. makeUserMessage({
  3971. sessionId: task.taskId,
  3972. messageId: "message_2",
  3973. text: "message 2",
  3974. }),
  3975. makeUserMessage({
  3976. sessionId: task.taskId,
  3977. messageId: "message_3",
  3978. text: "message 3",
  3979. }),
  3980. ],
  3981. }),
  3982. );
  3983. const snapshot = await service.getTaskSnapshot({
  3984. workspacePath: "/repo",
  3985. taskId: task.taskId,
  3986. messageLimit: 2,
  3987. });
  3988. expect(snapshot?.messages.map((message) => message.content)).toEqual([
  3989. "message 2",
  3990. "message 3",
  3991. ]);
  3992. expect(snapshot?.history?.truncatedBefore).toBe(true);
  3993. expect(snapshot?.history?.totalMessages).toBe(3);
  3994. });
  3995. it("restores legacy v2 task snapshots when the protocol session is missing", async () => {
  3996. const { agent, service } = createService();
  3997. const workspacePath = "/repo";
  3998. const taskId = "legacy_task";
  3999. const snapshotPath = getLegacyTaskSessionSnapshotPath(workspacePath, taskId);
  4000. mkdirSync(dirname(snapshotPath), { recursive: true });
  4001. writeFileSync(
  4002. snapshotPath,
  4003. JSON.stringify({
  4004. meta: {
  4005. taskId,
  4006. traceId: "trace_legacy",
  4007. title: "Legacy ACP task",
  4008. workspacePath,
  4009. createdAt: 10,
  4010. updatedAt: 20,
  4011. mode: "yolo",
  4012. provider: "glm",
  4013. },
  4014. messages: [
  4015. {
  4016. role: "user",
  4017. content: "old prompt",
  4018. timestamp: 10,
  4019. },
  4020. ],
  4021. }),
  4022. "utf-8",
  4023. );
  4024. vi.mocked(agent.resumeSession).mockRejectedValue(new Error(`Session not found: ${taskId}`));
  4025. const snapshot = await service.getTaskSnapshot({ workspacePath, taskId });
  4026. expect(snapshot?.meta).toMatchObject({
  4027. taskId,
  4028. title: "Legacy ACP task",
  4029. workspacePath,
  4030. status: "completed",
  4031. });
  4032. expect(snapshot?.messages.map((message) => message.content)).toEqual(["old prompt"]);
  4033. vi.mocked(agent.onDynamicSessionEvent).mockClear();
  4034. const disposable = service.onDynamicTaskEvent({
  4035. workspacePath,
  4036. taskId,
  4037. deliveryKind: "continuous",
  4038. })(() => undefined);
  4039. disposable.dispose();
  4040. expect(agent.onDynamicSessionEvent).not.toHaveBeenCalled();
  4041. });
  4042. it("upgrades legacy imported Claude snapshots to protocol sessions before model switching", async () => {
  4043. const { agent, service, taskIndexRepo } = createService();
  4044. const workspacePath = "/repo";
  4045. const taskId = "claude-import-590ccc622ab6db6bd9f1d7bf";
  4046. const snapshotPath = getLegacyTaskSessionSnapshotPath(workspacePath, taskId);
  4047. mkdirSync(dirname(snapshotPath), { recursive: true });
  4048. writeFileSync(
  4049. snapshotPath,
  4050. JSON.stringify({
  4051. meta: {
  4052. taskId,
  4053. traceId: "trace_claude_import",
  4054. title: "Claude imported task",
  4055. workspacePath,
  4056. createdAt: 10,
  4057. updatedAt: 20,
  4058. provider: "glm",
  4059. migrationSource: "claudeCode",
  4060. },
  4061. messages: [
  4062. {
  4063. role: "user",
  4064. content: "旧 Claude 提问",
  4065. timestamp: 10,
  4066. },
  4067. {
  4068. role: "assistant",
  4069. content: "旧 Claude 回答",
  4070. timestamp: 20,
  4071. },
  4072. ],
  4073. }),
  4074. "utf-8",
  4075. );
  4076. vi.mocked(agent.resumeSession).mockImplementation(async (params) => {
  4077. throw new Error(`Session not found: ${params.sessionId}`);
  4078. });
  4079. const snapshot = await service.getTaskSnapshot({ workspacePath, taskId });
  4080. expect(agent.createSession).toHaveBeenCalledWith(
  4081. expect.objectContaining({
  4082. workspacePath,
  4083. workspaceIdentity: undefined,
  4084. sessionId: taskId,
  4085. persistence: "immediate",
  4086. importedHistory: expect.objectContaining({
  4087. source: "claudeCode",
  4088. title: "Claude imported task",
  4089. messages: [
  4090. { role: "user", content: "旧 Claude 提问", timestamp: 10 },
  4091. { role: "assistant", content: "旧 Claude 回答", timestamp: 20 },
  4092. ],
  4093. }),
  4094. }),
  4095. );
  4096. expect(snapshot?.meta).toMatchObject({
  4097. taskId,
  4098. title: "Claude imported task",
  4099. workspacePath,
  4100. migrationSource: "claudeCode",
  4101. model: "glm/glm-4.6",
  4102. });
  4103. expect(snapshot?.messages.map((message) => message.content)).toEqual([
  4104. "旧 Claude 提问",
  4105. "旧 Claude 回答",
  4106. ]);
  4107. await expect(taskIndexRepo.getTaskMeta({ workspacePath, taskId })).resolves.toMatchObject({
  4108. taskId,
  4109. migrationSource: "claudeCode",
  4110. model: "glm/glm-4.6",
  4111. });
  4112. vi.mocked(agent.resumeSession).mockRestore();
  4113. await service.setModel({
  4114. taskId,
  4115. traceId: "trace_set_model",
  4116. modelSelection: { providerId: "glm", modelId: "glm-4.6" },
  4117. });
  4118. expect(agent.setModel).toHaveBeenCalledWith({
  4119. workspacePath,
  4120. workspaceIdentity: undefined,
  4121. sessionId: taskId,
  4122. model: { providerId: "glm", modelId: "glm-4.6" },
  4123. });
  4124. });
  4125. it("repairs empty protocol snapshots for imported Claude tasks from legacy backups", async () => {
  4126. const { agent, service } = createService();
  4127. const workspacePath = "/repo";
  4128. const taskId = "claude-import-empty-protocol";
  4129. const snapshotPath = getLegacyTaskSessionSnapshotPath(workspacePath, taskId);
  4130. mkdirSync(dirname(snapshotPath), { recursive: true });
  4131. writeFileSync(
  4132. snapshotPath,
  4133. JSON.stringify({
  4134. meta: {
  4135. taskId,
  4136. traceId: "trace_empty_protocol",
  4137. title: "Claude empty protocol",
  4138. workspacePath,
  4139. createdAt: 10,
  4140. updatedAt: 20,
  4141. migrationSource: "claudeCode",
  4142. },
  4143. messages: [
  4144. { role: "user", content: "旧问题", timestamp: 10 },
  4145. { role: "assistant", content: "旧回答", timestamp: 20 },
  4146. ],
  4147. }),
  4148. "utf-8",
  4149. );
  4150. vi.mocked(agent.resumeSession).mockResolvedValue(
  4151. makeSnapshot({
  4152. sessionId: taskId,
  4153. workspacePath,
  4154. title: "Claude empty protocol",
  4155. messages: [],
  4156. }),
  4157. );
  4158. const snapshot = await service.getTaskSnapshot({ workspacePath, taskId });
  4159. expect(agent.createSession).toHaveBeenCalledWith(
  4160. expect.objectContaining({
  4161. workspacePath,
  4162. sessionId: taskId,
  4163. persistence: "immediate",
  4164. importedHistory: expect.objectContaining({
  4165. source: "claudeCode",
  4166. messages: [
  4167. { role: "user", content: "旧问题", timestamp: 10 },
  4168. { role: "assistant", content: "旧回答", timestamp: 20 },
  4169. ],
  4170. }),
  4171. }),
  4172. );
  4173. expect(snapshot?.messages.map((message) => message.content)).toEqual(["旧问题", "旧回答"]);
  4174. expect(snapshot?.meta).toMatchObject({
  4175. taskId,
  4176. migrationSource: "claudeCode",
  4177. });
  4178. });
  4179. it("migrates legacy wrapper task ids to acp_session_id backed protocol sessions", async () => {
  4180. const { agent, service, taskIndexRepo } = createService();
  4181. const workspacePath = "/repo";
  4182. const taskId = "legacy_wrapper_task";
  4183. const acpSessionId = "sess_legacy_real";
  4184. await seedIndexedTask(taskIndexRepo, {
  4185. taskId,
  4186. provider: "glm",
  4187. workspacePath,
  4188. });
  4189. await seedLegacyAcpSessionId(taskIndexRepo, {
  4190. workspacePath,
  4191. taskId,
  4192. acpSessionId,
  4193. });
  4194. await expect(taskIndexRepo.getTaskMeta({ workspacePath, taskId })).resolves.toBeNull();
  4195. await expect(
  4196. taskIndexRepo.getTaskMeta({ workspacePath, taskId: acpSessionId }),
  4197. ).resolves.toMatchObject({
  4198. taskId: acpSessionId,
  4199. workspacePath,
  4200. provider: "glm",
  4201. });
  4202. const dbSnapshot = makeSnapshot({
  4203. sessionId: acpSessionId,
  4204. workspacePath,
  4205. title: "DB session",
  4206. messages: [
  4207. makeUserMessage({
  4208. sessionId: acpSessionId,
  4209. messageId: "msg_db_user",
  4210. text: "db prompt",
  4211. }),
  4212. ],
  4213. });
  4214. vi.mocked(agent.resumeSession).mockImplementation(async (params) => {
  4215. if (params.sessionId === acpSessionId) {
  4216. return dbSnapshot;
  4217. }
  4218. throw new Error(`Session not found: ${params.sessionId}`);
  4219. });
  4220. agent.reconcileSessionsIndexV4 = vi.fn(async () => ({
  4221. sessions: [
  4222. {
  4223. sessionId: acpSessionId,
  4224. exists: true as const,
  4225. deleted: false,
  4226. title: "DB session",
  4227. titleSource: "generated" as const,
  4228. createdAt: dbSnapshot.session.createdAt,
  4229. updatedAt: dbSnapshot.session.updatedAt,
  4230. },
  4231. ],
  4232. }));
  4233. const snapshot = await service.getTaskSnapshot({
  4234. workspacePath,
  4235. taskId: acpSessionId,
  4236. });
  4237. expect(snapshot?.meta).toMatchObject({
  4238. taskId: acpSessionId,
  4239. title: "DB session",
  4240. workspacePath,
  4241. model: "glm/glm-4.6",
  4242. thoughtLevel: "think",
  4243. });
  4244. expect(snapshot?.messages.map((message) => message.content)).toEqual(["db prompt"]);
  4245. expect(agent.resumeSession).toHaveBeenCalledWith({
  4246. workspacePath,
  4247. workspaceIdentity: undefined,
  4248. sessionId: acpSessionId,
  4249. });
  4250. const disposable = service.onDynamicTaskEvent({
  4251. workspacePath,
  4252. taskId: acpSessionId,
  4253. deliveryKind: "continuous",
  4254. })(() => undefined);
  4255. disposable.dispose();
  4256. expect(agent.onDynamicSessionEvent).toHaveBeenCalledWith({
  4257. workspacePath,
  4258. workspaceIdentity: undefined,
  4259. sessionId: acpSessionId,
  4260. deliveryKind: "desktop-continuous",
  4261. includeSnapshot: false,
  4262. });
  4263. await service.sendPrompt({
  4264. taskId: acpSessionId,
  4265. traceId: "input_1",
  4266. content: "continue",
  4267. });
  4268. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith({
  4269. workspacePath,
  4270. workspaceIdentity: undefined,
  4271. envelope: expect.objectContaining({
  4272. type: "sendText",
  4273. sessionId: acpSessionId,
  4274. commandId: "input_1",
  4275. payload: { text: "continue", heldQueueDisposition: "keepQueueAndSend" },
  4276. }),
  4277. });
  4278. });
  4279. it("maps ZCode Protocol context projection events to legacy usage_update", async () => {
  4280. const { eventEmitter, service } = createService();
  4281. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  4282. const received: ZCodeStreamEvent[] = [];
  4283. const disposable = service.onDynamicTaskEvent({
  4284. workspacePath: "/repo",
  4285. taskId: task.taskId,
  4286. deliveryKind: "continuous",
  4287. })((event) => {
  4288. received.push(event);
  4289. });
  4290. eventEmitter.fire({
  4291. type: "session.event",
  4292. event: {
  4293. eventId: "evt_usage",
  4294. sessionId: task.taskId,
  4295. seq: 1,
  4296. timestamp: 2,
  4297. traceId: "trace_usage",
  4298. type: "session.updated",
  4299. payload: {
  4300. contextUsed: 24000,
  4301. contextWindow: 128000,
  4302. },
  4303. },
  4304. });
  4305. disposable.dispose();
  4306. expect(received).toContainEqual({
  4307. type: "usage_update",
  4308. taskId: task.taskId,
  4309. traceId: "trace_usage",
  4310. used: 24000,
  4311. size: 128000,
  4312. cost: null,
  4313. });
  4314. });
  4315. it.each([
  4316. { streamed: "", expected: "完整项目说明" },
  4317. { streamed: "完整项目", expected: "说明" },
  4318. { streamed: "完整项目说明", expected: "" },
  4319. ])(
  4320. "补齐工具调用后缺失的终态正文且不重复已收到的部分:$streamed",
  4321. async ({ streamed, expected }) => {
  4322. const { eventEmitter, service } = createService();
  4323. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  4324. const received: ZCodeStreamEvent[] = [];
  4325. const subscription = service.onDynamicTaskEvent({
  4326. workspacePath: "/repo",
  4327. taskId: task.taskId,
  4328. deliveryKind: "bot-channel-continuous",
  4329. })((event) => {
  4330. received.push(event);
  4331. });
  4332. let seq = 0;
  4333. const emit = (
  4334. type: ZCodeSessionEvent["type"],
  4335. payload: Record<string, unknown>,
  4336. turnId = "turn_repair",
  4337. ) => {
  4338. eventEmitter.fire({
  4339. type: "session.event",
  4340. event: {
  4341. eventId: `repair_${++seq}`,
  4342. sessionId: task.taskId,
  4343. turnId,
  4344. seq,
  4345. timestamp: seq,
  4346. traceId: turnId,
  4347. type,
  4348. payload,
  4349. },
  4350. });
  4351. };
  4352. emit("turn.started", { inputId: "input_repair" });
  4353. emit("session.updated", {
  4354. kind: "text_delta",
  4355. delta: "我来看一下项目目录的内容。",
  4356. assistantMessageId: "preface",
  4357. });
  4358. emit("tool.updated", {
  4359. kind: "scheduled",
  4360. toolCallId: "read_project",
  4361. toolName: "Read",
  4362. input: {},
  4363. });
  4364. if (streamed)
  4365. emit("session.updated", {
  4366. kind: "text_delta",
  4367. delta: streamed,
  4368. assistantMessageId: "answer",
  4369. });
  4370. const before = received.length;
  4371. emit("turn.completed", {
  4372. inputId: "input_repair",
  4373. response: "完整项目说明",
  4374. resultType: "success",
  4375. });
  4376. const terminal = received.slice(before);
  4377. expect(
  4378. terminal
  4379. .filter((event) => event.type === "agent_message_chunk")
  4380. .map((event) => event.content)
  4381. .join(""),
  4382. ).toBe(expected);
  4383. expect(terminal.at(-1)?.type).toBe("task_complete");
  4384. emit("turn.started", { inputId: "input_next" }, "turn_next");
  4385. const next = received.length;
  4386. emit(
  4387. "turn.completed",
  4388. { inputId: "input_next", response: "完整项目说明", resultType: "success" },
  4389. "turn_next",
  4390. );
  4391. expect(received.slice(next)).toContainEqual(
  4392. expect.objectContaining({
  4393. type: "agent_message_chunk",
  4394. content: "完整项目说明",
  4395. inputId: "input_next",
  4396. }),
  4397. );
  4398. subscription.dispose();
  4399. },
  4400. );
  4401. it("不同 assistant message 的正文独立核对,不受前言或子代理文字影响", async () => {
  4402. const { eventEmitter, service } = createService();
  4403. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  4404. const received: ZCodeStreamEvent[] = [];
  4405. const subscription = service.onDynamicTaskEvent({
  4406. workspacePath: "/repo",
  4407. taskId: task.taskId,
  4408. deliveryKind: "bot-channel-continuous",
  4409. })((event) => {
  4410. received.push(event);
  4411. });
  4412. let seq = 0;
  4413. const emit = (
  4414. payload: Record<string, unknown>,
  4415. type: "session.updated" | "turn.completed" = "session.updated",
  4416. ) =>
  4417. eventEmitter.fire({
  4418. type: "session.event",
  4419. event: {
  4420. eventId: `message_${++seq}`,
  4421. sessionId: task.taskId,
  4422. turnId: "message_turn",
  4423. seq,
  4424. timestamp: seq,
  4425. traceId: "message_turn",
  4426. type,
  4427. payload,
  4428. },
  4429. });
  4430. emit({ kind: "text_delta", assistantMessageId: "preface", delta: "先检查。" });
  4431. emit({ kind: "text_delta", assistantMessageId: "answer", delta: "最终" });
  4432. emit({
  4433. kind: "text_delta",
  4434. assistantMessageId: "child",
  4435. parentToolUseId: "agent_tool",
  4436. delta: "子代理内容",
  4437. });
  4438. const before = received.length;
  4439. emit({ response: "最终回答", resultType: "success" }, "turn.completed");
  4440. expect(received.slice(before)).toEqual([
  4441. expect.objectContaining({ type: "agent_message_chunk", content: "回答" }),
  4442. expect.objectContaining({ type: "task_complete" }),
  4443. ]);
  4444. subscription.dispose();
  4445. });
  4446. it("uses prompt inputId as per-turn traceId for session stream events", async () => {
  4447. const { agent, eventEmitter, service } = createService();
  4448. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  4449. const received: ZCodeStreamEvent[] = [];
  4450. const disposable = service.onDynamicTaskEvent({
  4451. workspacePath: "/repo",
  4452. taskId: task.taskId,
  4453. deliveryKind: "continuous",
  4454. })((event) => {
  4455. received.push(event);
  4456. });
  4457. await service.sendPrompt({
  4458. taskId: task.taskId,
  4459. traceId: "input_turn_1",
  4460. content: "continue",
  4461. });
  4462. expect(agent.sendConversationCommandV4).toHaveBeenCalledWith(
  4463. expect.objectContaining({
  4464. envelope: expect.objectContaining({ commandId: "input_turn_1" }),
  4465. }),
  4466. );
  4467. eventEmitter.fire({
  4468. type: "session.event",
  4469. event: {
  4470. eventId: "evt_stream",
  4471. sessionId: task.taskId,
  4472. turnId: "turn_1",
  4473. seq: 1,
  4474. timestamp: 2,
  4475. traceId: "runtime_trace_1",
  4476. type: "session.updated",
  4477. payload: { kind: "text_delta", delta: "hello" },
  4478. },
  4479. });
  4480. eventEmitter.fire({
  4481. type: "session.event",
  4482. event: {
  4483. eventId: "evt_tool",
  4484. sessionId: task.taskId,
  4485. turnId: "turn_1",
  4486. seq: 2,
  4487. timestamp: 3,
  4488. traceId: "runtime_trace_1",
  4489. type: "tool.updated",
  4490. payload: {
  4491. kind: "scheduled",
  4492. toolCallId: "call_1",
  4493. toolName: "Read",
  4494. input: { filePath: "/repo/app.ts" },
  4495. },
  4496. },
  4497. });
  4498. eventEmitter.fire({
  4499. type: "session.event",
  4500. event: {
  4501. eventId: "evt_done",
  4502. sessionId: task.taskId,
  4503. turnId: "turn_1",
  4504. seq: 3,
  4505. timestamp: 4,
  4506. traceId: "runtime_trace_1",
  4507. type: "turn.completed",
  4508. payload: { inputId: "input_turn_1", resultType: "success" },
  4509. },
  4510. });
  4511. disposable.dispose();
  4512. expect(received).toContainEqual(
  4513. expect.objectContaining({
  4514. type: "agent_message_chunk",
  4515. traceId: "input_turn_1",
  4516. inputId: "input_turn_1",
  4517. }),
  4518. );
  4519. expect(received).toContainEqual(
  4520. expect.objectContaining({
  4521. type: "tool_call",
  4522. traceId: "input_turn_1",
  4523. inputId: "input_turn_1",
  4524. toolId: "call_1",
  4525. }),
  4526. );
  4527. expect(received).toContainEqual(
  4528. expect.objectContaining({
  4529. type: "task_complete",
  4530. traceId: "input_turn_1",
  4531. inputId: "input_turn_1",
  4532. }),
  4533. );
  4534. });
  4535. it("maps main turn model usage with context window to legacy usage_update", async () => {
  4536. const { eventEmitter, service } = createService();
  4537. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  4538. const received: ZCodeStreamEvent[] = [];
  4539. const disposable = service.onDynamicTaskEvent({
  4540. workspacePath: "/repo",
  4541. taskId: task.taskId,
  4542. deliveryKind: "continuous",
  4543. })((event) => {
  4544. received.push(event);
  4545. });
  4546. eventEmitter.fire({
  4547. type: "session.event",
  4548. event: {
  4549. eventId: "evt_model_usage",
  4550. sessionId: task.taskId,
  4551. seq: 1,
  4552. timestamp: 2,
  4553. traceId: "trace_model_usage",
  4554. type: "session.updated",
  4555. payload: {
  4556. contextWindow: 1_000_000,
  4557. querySource: "main_turn",
  4558. usage: {
  4559. inputTokens: 279454,
  4560. outputTokens: 177,
  4561. totalTokens: 279631,
  4562. cacheReadTokens: 1000,
  4563. cacheWriteTokens: 200,
  4564. cacheHitRate: 0.25,
  4565. },
  4566. contextUsageBreakdown: [
  4567. { source: "messages", chars: 1200 },
  4568. { source: "system_tool_schemas", chars: 300 },
  4569. ],
  4570. },
  4571. },
  4572. });
  4573. disposable.dispose();
  4574. expect(received).toContainEqual({
  4575. type: "usage_update",
  4576. taskId: task.taskId,
  4577. traceId: "trace_model_usage",
  4578. used: 279631,
  4579. size: 1_000_000,
  4580. cost: null,
  4581. cache: {
  4582. inputTokens: 279454,
  4583. cacheReadTokens: 1000,
  4584. cacheWriteTokens: 200,
  4585. latestHitRate: 0.25,
  4586. hitRate: 0.25,
  4587. },
  4588. breakdown: [
  4589. { source: "messages", chars: 1200 },
  4590. { source: "system_tool_schemas", chars: 300 },
  4591. ],
  4592. });
  4593. expect(received).toContainEqual({
  4594. type: "task_token_usage_delta",
  4595. taskId: task.taskId,
  4596. traceId: "trace_model_usage",
  4597. eventKey: "evt_model_usage",
  4598. eventId: "evt_model_usage",
  4599. querySource: "main_turn",
  4600. usage: {
  4601. inputTokens: 279454,
  4602. outputTokens: 177,
  4603. totalTokens: 279631,
  4604. reasoningTokens: undefined,
  4605. cachedInputTokens: 1000,
  4606. cachedWriteInputTokens: 200,
  4607. },
  4608. });
  4609. });
  4610. it("maps aggregate main turn cache hit usage to legacy usage_update", async () => {
  4611. const { eventEmitter, service } = createService();
  4612. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  4613. const received: ZCodeStreamEvent[] = [];
  4614. const disposable = service.onDynamicTaskEvent({
  4615. workspacePath: "/repo",
  4616. taskId: task.taskId,
  4617. deliveryKind: "continuous",
  4618. })((event) => {
  4619. received.push(event);
  4620. });
  4621. eventEmitter.fire({
  4622. type: "session.event",
  4623. event: {
  4624. eventId: "evt_model_usage_average",
  4625. sessionId: task.taskId,
  4626. seq: 1,
  4627. timestamp: 2,
  4628. traceId: "trace_model_usage_average",
  4629. type: "session.updated",
  4630. payload: {
  4631. contextWindow: 1_000_000,
  4632. querySource: "main_turn",
  4633. cacheHit: {
  4634. inputTokens: 200,
  4635. cacheReadTokens: 80,
  4636. cacheWriteTokens: 10,
  4637. latestHitRate: 0.4,
  4638. hitRate: 0.3,
  4639. hitRateRequestCount: 2,
  4640. totalInputTokens: 500,
  4641. totalCacheReadTokens: 150,
  4642. totalCacheWriteTokens: 25,
  4643. },
  4644. usage: {
  4645. inputTokens: 200,
  4646. outputTokens: 20,
  4647. totalTokens: 220,
  4648. cacheReadTokens: 80,
  4649. cacheWriteTokens: 10,
  4650. },
  4651. },
  4652. },
  4653. });
  4654. disposable.dispose();
  4655. expect(received).toContainEqual({
  4656. type: "usage_update",
  4657. taskId: task.taskId,
  4658. traceId: "trace_model_usage_average",
  4659. used: 220,
  4660. size: 1_000_000,
  4661. cost: null,
  4662. cache: {
  4663. inputTokens: 200,
  4664. cacheReadTokens: 80,
  4665. cacheWriteTokens: 10,
  4666. latestHitRate: 0.4,
  4667. hitRate: 0.3,
  4668. hitRateRequestCount: 2,
  4669. totalInputTokens: 500,
  4670. totalCacheReadTokens: 150,
  4671. totalCacheWriteTokens: 25,
  4672. },
  4673. });
  4674. });
  4675. it("prefers real main turn model usage over projected context used", async () => {
  4676. const { eventEmitter, service } = createService();
  4677. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  4678. const received: ZCodeStreamEvent[] = [];
  4679. const disposable = service.onDynamicTaskEvent({
  4680. workspacePath: "/repo",
  4681. taskId: task.taskId,
  4682. deliveryKind: "continuous",
  4683. })((event) => {
  4684. received.push(event);
  4685. });
  4686. eventEmitter.fire({
  4687. type: "session.event",
  4688. event: {
  4689. eventId: "evt_model_usage_projection",
  4690. sessionId: task.taskId,
  4691. seq: 1,
  4692. timestamp: 2,
  4693. traceId: "trace_model_usage_projection",
  4694. type: "session.updated",
  4695. payload: {
  4696. contextUsed: 64000,
  4697. contextWindow: 1_000_000,
  4698. querySource: "main_turn",
  4699. usage: {
  4700. inputTokens: 12345,
  4701. outputTokens: 77,
  4702. totalTokens: 12422,
  4703. },
  4704. },
  4705. },
  4706. });
  4707. disposable.dispose();
  4708. expect(received).toContainEqual({
  4709. type: "usage_update",
  4710. taskId: task.taskId,
  4711. traceId: "trace_model_usage_projection",
  4712. used: 12422,
  4713. size: 1_000_000,
  4714. cost: null,
  4715. });
  4716. expect(received).toContainEqual({
  4717. type: "task_token_usage_delta",
  4718. taskId: task.taskId,
  4719. traceId: "trace_model_usage_projection",
  4720. eventKey: "evt_model_usage_projection",
  4721. eventId: "evt_model_usage_projection",
  4722. querySource: "main_turn",
  4723. usage: {
  4724. inputTokens: 12345,
  4725. outputTokens: 77,
  4726. totalTokens: 12422,
  4727. reasoningTokens: undefined,
  4728. cachedInputTokens: undefined,
  4729. cachedWriteInputTokens: undefined,
  4730. },
  4731. });
  4732. });
  4733. it("does not map sidecar model usage to legacy usage_update", async () => {
  4734. const { eventEmitter, service } = createService();
  4735. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  4736. const received: ZCodeStreamEvent[] = [];
  4737. const disposable = service.onDynamicTaskEvent({
  4738. workspacePath: "/repo",
  4739. taskId: task.taskId,
  4740. deliveryKind: "continuous",
  4741. })((event) => {
  4742. received.push(event);
  4743. });
  4744. eventEmitter.fire({
  4745. type: "session.event",
  4746. event: {
  4747. eventId: "evt_title_usage",
  4748. sessionId: task.taskId,
  4749. seq: 1,
  4750. timestamp: 2,
  4751. traceId: "trace_title_usage",
  4752. type: "session.updated",
  4753. payload: {
  4754. contextWindow: 1_000_000,
  4755. querySource: "session_title",
  4756. usage: {
  4757. inputTokens: 89,
  4758. outputTokens: 84,
  4759. totalTokens: 173,
  4760. },
  4761. },
  4762. },
  4763. });
  4764. disposable.dispose();
  4765. expect(received).not.toContainEqual(
  4766. expect.objectContaining({
  4767. type: "usage_update",
  4768. traceId: "trace_title_usage",
  4769. }),
  4770. );
  4771. expect(received).toContainEqual({
  4772. type: "task_token_usage_delta",
  4773. taskId: task.taskId,
  4774. traceId: "trace_title_usage",
  4775. eventKey: "evt_title_usage",
  4776. eventId: "evt_title_usage",
  4777. querySource: "session_title",
  4778. usage: {
  4779. inputTokens: 89,
  4780. outputTokens: 84,
  4781. totalTokens: 173,
  4782. reasoningTokens: undefined,
  4783. cachedInputTokens: undefined,
  4784. cachedWriteInputTokens: undefined,
  4785. },
  4786. });
  4787. });
  4788. it("maps ZCode model retry status to apiRetry stream events and runtime snapshots", async () => {
  4789. const { eventEmitter, service } = createService();
  4790. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  4791. const received: ZCodeStreamEvent[] = [];
  4792. const disposable = service.onDynamicTaskEvent({
  4793. workspacePath: "/repo",
  4794. taskId: task.taskId,
  4795. deliveryKind: "continuous",
  4796. })((event) => {
  4797. received.push(event);
  4798. });
  4799. eventEmitter.fire({
  4800. type: "session.event",
  4801. event: {
  4802. eventId: "evt_retry",
  4803. sessionId: task.taskId,
  4804. seq: 1,
  4805. timestamp: 2,
  4806. traceId: "trace_retry",
  4807. type: "session.updated",
  4808. payload: {
  4809. type: "model_retry_scheduled",
  4810. attempt: 1,
  4811. maxAttempts: 4,
  4812. delayMs: 2_000,
  4813. statusCode: 429,
  4814. message: "rate limited",
  4815. },
  4816. },
  4817. });
  4818. expect(received).toContainEqual({
  4819. type: "session_info_update",
  4820. taskId: task.taskId,
  4821. traceId: "trace_retry",
  4822. apiRetry: {
  4823. kind: "api_retry",
  4824. attempt: 1,
  4825. maxRetries: 3,
  4826. retryDelayMs: 2_000,
  4827. errorStatus: 429,
  4828. error: "rate limited",
  4829. },
  4830. });
  4831. await expect(
  4832. service.getTaskSnapshot({ workspacePath: "/repo", taskId: task.taskId }),
  4833. ).resolves.toMatchObject({
  4834. runtime: {
  4835. apiRetry: {
  4836. kind: "api_retry",
  4837. attempt: 1,
  4838. maxRetries: 3,
  4839. retryDelayMs: 2_000,
  4840. errorStatus: 429,
  4841. error: "rate limited",
  4842. },
  4843. },
  4844. });
  4845. const retryStartedReceivedIndex = received.length;
  4846. eventEmitter.fire({
  4847. type: "session.event",
  4848. event: {
  4849. eventId: "evt_retry_started",
  4850. sessionId: task.taskId,
  4851. seq: 2,
  4852. timestamp: 3,
  4853. traceId: "trace_retry",
  4854. type: "session.updated",
  4855. payload: {
  4856. type: "model_request_started",
  4857. attempt: 2,
  4858. maxAttempts: 4,
  4859. requestId: "request_retry",
  4860. },
  4861. },
  4862. });
  4863. const retryStartedEvents = received.slice(retryStartedReceivedIndex);
  4864. expect(retryStartedEvents).toContainEqual(
  4865. expect.objectContaining({
  4866. type: "task_network_debug_status",
  4867. taskId: task.taskId,
  4868. traceId: "trace_retry",
  4869. eventKey: "evt_retry_started",
  4870. statusType: "model_request_started",
  4871. attempt: 2,
  4872. maxAttempts: 4,
  4873. }),
  4874. );
  4875. expect(retryStartedEvents).not.toContainEqual({
  4876. type: "session_info_update",
  4877. taskId: task.taskId,
  4878. traceId: "trace_retry",
  4879. apiRetry: null,
  4880. });
  4881. await expect(
  4882. service.getTaskSnapshot({ workspacePath: "/repo", taskId: task.taskId }),
  4883. ).resolves.toMatchObject({
  4884. runtime: {
  4885. apiRetry: {
  4886. kind: "api_retry",
  4887. attempt: 1,
  4888. maxRetries: 3,
  4889. retryDelayMs: 2_000,
  4890. errorStatus: 429,
  4891. error: "rate limited",
  4892. },
  4893. },
  4894. });
  4895. const retryProgressReceivedIndex = received.length;
  4896. eventEmitter.fire({
  4897. type: "session.event",
  4898. event: {
  4899. eventId: "evt_retry_progress",
  4900. sessionId: task.taskId,
  4901. seq: 3,
  4902. timestamp: 4,
  4903. traceId: "trace_retry",
  4904. type: "session.updated",
  4905. payload: {
  4906. kind: "text_delta",
  4907. delta: "recovered",
  4908. assistantMessageId: "msg_retry",
  4909. },
  4910. },
  4911. });
  4912. const retryProgressEvents = received.slice(retryProgressReceivedIndex);
  4913. expect(retryProgressEvents).toContainEqual({
  4914. type: "session_info_update",
  4915. taskId: task.taskId,
  4916. traceId: "trace_retry",
  4917. apiRetry: null,
  4918. });
  4919. expect(retryProgressEvents).toContainEqual({
  4920. type: "agent_message_chunk",
  4921. taskId: task.taskId,
  4922. traceId: "trace_retry",
  4923. messageId: "msg_retry",
  4924. content: "recovered",
  4925. });
  4926. await expect(
  4927. service.getTaskSnapshot({ workspacePath: "/repo", taskId: task.taskId }),
  4928. ).resolves.toMatchObject({
  4929. runtime: {
  4930. apiRetry: null,
  4931. },
  4932. });
  4933. eventEmitter.fire({
  4934. type: "session.event",
  4935. event: {
  4936. eventId: "evt_stream_recovery_retry",
  4937. sessionId: task.taskId,
  4938. seq: 4,
  4939. timestamp: 5,
  4940. traceId: "trace_retry",
  4941. type: "session.updated",
  4942. payload: {
  4943. type: "model_request_started",
  4944. attempt: 1,
  4945. maxAttempts: 11,
  4946. requestId: "request_recovery",
  4947. streamRecovery: {
  4948. attemptId: "stream_attempt_1",
  4949. anchorId: "anchor_1",
  4950. maxRetries: 10,
  4951. recoveredFromRequestId: "request_failed",
  4952. retryNumber: 3,
  4953. },
  4954. },
  4955. },
  4956. });
  4957. expect(received).toContainEqual({
  4958. type: "session_info_update",
  4959. taskId: task.taskId,
  4960. traceId: "trace_retry",
  4961. apiRetry: {
  4962. kind: "api_retry",
  4963. attempt: 3,
  4964. maxRetries: 10,
  4965. retryDelayMs: 0,
  4966. errorStatus: null,
  4967. error: "Model stream recovery retry started",
  4968. },
  4969. });
  4970. await expect(
  4971. service.getTaskSnapshot({ workspacePath: "/repo", taskId: task.taskId }),
  4972. ).resolves.toMatchObject({
  4973. runtime: {
  4974. apiRetry: {
  4975. kind: "api_retry",
  4976. attempt: 3,
  4977. maxRetries: 10,
  4978. retryDelayMs: 0,
  4979. errorStatus: null,
  4980. error: "Model stream recovery retry started",
  4981. },
  4982. },
  4983. });
  4984. eventEmitter.fire({
  4985. type: "session.event",
  4986. event: {
  4987. eventId: "evt_stream_recovery_progress",
  4988. sessionId: task.taskId,
  4989. seq: 5,
  4990. timestamp: 6,
  4991. traceId: "trace_retry",
  4992. type: "streamRecovery.updated",
  4993. payload: {
  4994. attemptId: "stream_attempt_2",
  4995. failedRequestId: "request_failed",
  4996. maxRetries: 10,
  4997. recoveredFromRequestId: "request_failed",
  4998. retryNumber: 4,
  4999. streamMode: "sse",
  5000. },
  5001. },
  5002. });
  5003. expect(received).toContainEqual({
  5004. type: "session_info_update",
  5005. taskId: task.taskId,
  5006. traceId: "trace_retry",
  5007. apiRetry: {
  5008. kind: "api_retry",
  5009. attempt: 4,
  5010. maxRetries: 10,
  5011. retryDelayMs: 0,
  5012. errorStatus: null,
  5013. error: "Model stream recovery retry started",
  5014. },
  5015. });
  5016. await expect(
  5017. service.getTaskSnapshot({ workspacePath: "/repo", taskId: task.taskId }),
  5018. ).resolves.toMatchObject({
  5019. runtime: {
  5020. apiRetry: {
  5021. kind: "api_retry",
  5022. attempt: 4,
  5023. maxRetries: 10,
  5024. retryDelayMs: 0,
  5025. errorStatus: null,
  5026. error: "Model stream recovery retry started",
  5027. },
  5028. },
  5029. });
  5030. eventEmitter.fire({
  5031. type: "session.event",
  5032. event: {
  5033. eventId: "evt_retry_clear",
  5034. sessionId: task.taskId,
  5035. seq: 6,
  5036. timestamp: 7,
  5037. traceId: "trace_retry",
  5038. type: "session.updated",
  5039. payload: {
  5040. type: "model_request_completed",
  5041. attempt: 2,
  5042. maxAttempts: 4,
  5043. },
  5044. },
  5045. });
  5046. disposable.dispose();
  5047. expect(received).toContainEqual({
  5048. type: "session_info_update",
  5049. taskId: task.taskId,
  5050. traceId: "trace_retry",
  5051. apiRetry: null,
  5052. });
  5053. await expect(
  5054. service.getTaskSnapshot({ workspacePath: "/repo", taskId: task.taskId }),
  5055. ).resolves.toMatchObject({
  5056. runtime: {
  5057. apiRetry: null,
  5058. },
  5059. });
  5060. });
  5061. it("keeps pinned state in sqlite without resuming the agent session", async () => {
  5062. const { agent, service } = createService();
  5063. const task = await service.createTask({ workspacePath: "/repo", provider: "glm" });
  5064. vi.mocked(agent.resumeSession).mockClear();
  5065. await service.setTaskPinned({
  5066. workspacePath: "/repo",
  5067. taskId: task.taskId,
  5068. pinned: true,
  5069. });
  5070. const pinned = await service.listPinnedTasks({ workspacePath: "/repo" });
  5071. const active = await service.listTasks({ workspacePath: "/repo" });
  5072. expect(agent.resumeSession).not.toHaveBeenCalled();
  5073. expect(pinned.map((item) => item.taskId)).toEqual([task.taskId]);
  5074. expect(active).toEqual([]);
  5075. });
  5076. });