zcodeLegacyTaskCompatTaskIndex.test.ts 181 KB

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