| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705 |
- import {
- mkdir,
- mkdtemp,
- open,
- readdir,
- readFile,
- realpath,
- rm,
- stat,
- symlink,
- unlink,
- writeFile,
- } from "node:fs/promises";
- import { tmpdir } from "node:os";
- import { join, win32 } from "node:path";
- import { execFileSync } from "node:child_process";
- import iconv from "iconv-lite";
- import { setTimeout as sleep } from "node:timers/promises";
- import { describe, expect, it, vi } from "vitest";
- const { statfsMock } = vi.hoisted(() => ({
- statfsMock: vi.fn(),
- }));
- vi.mock("node:fs/promises", async (importOriginal) => {
- const actual = await importOriginal<typeof import("node:fs/promises")>();
- statfsMock.mockImplementation(actual.statfs);
- return {
- ...actual,
- statfs: statfsMock,
- };
- });
- import {
- applyResolvedShellCommandForTest,
- buildExecutionEnv,
- decodeExecutionOutputBuffer,
- NodeExecutionAdapter,
- resolveExecutionCommand,
- setResolvedShellLoginMode,
- } from "../src/exec/index.js";
- import {
- resolveEffectiveBashShellSelection,
- resolveWindowsGitBashShell,
- } from "../src/exec/bash-shell-provider.js";
- import { resolveBashMaxOutputLength } from "../src/exec/bash-output-policy.js";
- import { createCwdCapturePlan, normalizeCapturedCwdForHost } from "../src/exec/cwd-capture.js";
- import {
- type BackgroundExecutionSnapshot,
- type BackgroundExecutionStartResult,
- gitBashPathToWindowsPath,
- type ExecutionEvent,
- type ExecutionResult,
- type ExecutionRequest,
- type ExecutionRunOptions,
- windowsPathToGitBashPath,
- } from "@zcode/contracts";
- import { ZCODE_NO_PROXY_ENV_KEY, ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY } from "@zcode/shared";
- import { discoverWindowsGitBash } from "@zcode/shared/node";
- import * as sharedNode from "@zcode/shared/node";
- const POSIX_BASH_PATH =
- process.platform === "win32"
- ? undefined
- : findExecutable(["bash", "/bin/bash", "/usr/bin/bash", "/usr/local/bin/bash"]);
- const WINDOWS_GIT_BASH_PATH =
- process.platform === "win32" ? await resolveWindowsGitBashShell(process.env) : undefined;
- function findExecutable(candidates: Array<string | undefined>): string | undefined {
- return candidates.find((candidate) => candidate !== undefined && commandExists(candidate));
- }
- function commandExists(command: string): command is string {
- try {
- execFileSync(command, ["--version"], { stdio: "ignore" });
- return true;
- } catch {
- return false;
- }
- }
- type BashBackgroundLifecycleCapableAdapter = NodeExecutionAdapter & {
- runBashWithBackgroundLifecycle?: (
- request: ExecutionRequest,
- lifecycle: { mode: "explicit" | "auto_on_timeout" },
- options?: ExecutionRunOptions,
- ) => Promise<
- | {
- kind: "foreground";
- result: ExecutionResult;
- }
- | {
- kind: "backgrounded";
- task: BackgroundExecutionStartResult;
- }
- >;
- waitForBackgroundTask?: (
- taskId: string,
- options?: { signal?: AbortSignal },
- ) => Promise<BackgroundExecutionSnapshot | undefined>;
- };
- describe("NodeExecutionAdapter", () => {
- it.each(["abort", "close"] as const)(
- "does not initialize shell snapshots when cancelled during Windows Git Bash discovery (%s)",
- async (stopMode) => {
- const root = await mkdtemp(join(tmpdir(), "zcode-discovery-cancel-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- platform: "win32",
- processEnv: {},
- });
- const controller = new AbortController();
- const discoveryEntered = Promise.withResolvers<void>();
- const discoveryReleased =
- Promise.withResolvers<Awaited<ReturnType<typeof discoverWindowsGitBash>>>();
- const discover = vi.spyOn(sharedNode, "discoverWindowsGitBash").mockImplementation(() => {
- discoveryEntered.resolve();
- return discoveryReleased.promise;
- });
- const snapshots = (
- adapter as unknown as {
- shellInitSnapshots: { getOrCreate: () => Promise<undefined> };
- }
- ).shellInitSnapshots;
- const getOrCreate = vi.spyOn(snapshots, "getOrCreate").mockResolvedValue(undefined);
- const events: ExecutionEvent[] = [];
- let running: Promise<ExecutionResult> | undefined;
- let closing: Promise<void> | undefined;
- try {
- running = adapter.run(
- { command: { mode: "shell", command: "printf unexpected", shellProfile: "posix-bash" } },
- {
- signal: controller.signal,
- onEvent: (event) => {
- events.push(event);
- },
- },
- );
- await discoveryEntered.promise;
- if (stopMode === "abort") controller.abort();
- else closing = adapter.close();
- discoveryReleased.resolve({ path: "D:\\IsolatedGit\\bin\\bash.exe", source: "system" });
- expect(await running).toMatchObject({ status: "cancelled", cancelled: true });
- await closing;
- // 新增发现 await 期间可以取消;恢复准备时必须先检查取消,不能再启动 shell 初始化执行用户 rc。
- expect(getOrCreate).not.toHaveBeenCalled();
- expect(events.some((event) => event.type === "started")).toBe(false);
- } finally {
- discoveryReleased.resolve(undefined);
- await running;
- discover.mockRestore();
- getOrCreate.mockRestore();
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it("auto-backgrounds a foreground command when its timeout elapses", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- progressIntervalMs: 10,
- progressThresholdMs: 1,
- });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('late'), 60)"],
- },
- timeoutMs: 10,
- outputLimit: {
- persistOutput: "always",
- },
- trace: {
- sessionId: "exec-auto-background-session",
- attributes: {
- toolCallId: "toolu_auto_background",
- },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("backgrounded");
- expect(result.task.taskId).toMatch(/^exec_/u);
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.result?.stdout.text).toBe("late");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("keeps explicit background execution alive after its input timeout", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-timeout-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('survived'), 80)"],
- },
- timeoutMs: 5,
- trace: {
- sessionId: "exec-explicit-background-timeout-session",
- attributes: { toolCallId: "toolu_explicit_background_timeout" },
- } as any,
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- await sleep(25);
- expect((await capable.getBackgroundTask(result.task.taskId))?.status).toBe("running");
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.result?.stdout.text).toBe("survived");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("detaches parent abort after an explicit background commit", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-detach-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const parentTurn = new AbortController();
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('detached'), 70)"],
- },
- timeoutMs: 5,
- trace: {
- sessionId: "exec-explicit-background-detach-session",
- attributes: { toolCallId: "toolu_explicit_background_detach" },
- } as any,
- },
- { mode: "explicit" },
- { signal: parentTurn.signal },
- );
- expect(result.kind).toBe("backgrounded");
- parentTurn.abort();
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.result?.stdout.text).toBe("detached");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("still allows an explicit lifecycle task to be stopped directly", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-stop-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('unexpected'), 10_000)"],
- },
- timeoutMs: 5,
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- const stopped = await capable.cancelBackgroundTask(result.task.taskId);
- expect(stopped?.status).toBe("cancelled");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH || process.platform === "win32")(
- "kills a cooperative Bash descendant outside the root process group",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-cross-pgid-stop-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir,
- progressIntervalMs: 10,
- progressThresholdMs: 0,
- });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- let launcherPid = Number.NaN;
- let workerPid = Number.NaN;
- const workerScript = [
- "process.stdout.write('worker:' + process.pid + '\\n');",
- "setInterval(() => {}, 10_000);",
- ].join("");
- const launcherScript = [
- "const { spawn } = require('node:child_process');",
- "process.stdout.write('launcher:' + process.pid + '\\n');",
- `const worker = spawn(process.execPath, ['-e', ${JSON.stringify(workerScript)}], { stdio: ['ignore', 'inherit', 'inherit'] });`,
- "worker.on('exit', () => process.exit());",
- "setInterval(() => {}, 10_000);",
- ].join("");
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: `set -m; ${quotePosixShellArgument(process.execPath)} -e ${quotePosixShellArgument(launcherScript)} & wait`,
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- let runningSnapshot = await adapter.getBackgroundTask(result.task.taskId);
- for (let attempt = 0; attempt < 100; attempt += 1) {
- const output = await readFile(result.task.outputPath!, "utf8");
- launcherPid = Number(/launcher:(\d+)/u.exec(output)?.[1]);
- workerPid = Number(/worker:(\d+)/u.exec(output)?.[1]);
- if (
- Number.isInteger(launcherPid) &&
- launcherPid > 0 &&
- Number.isInteger(workerPid) &&
- workerPid > 0
- ) {
- break;
- }
- await sleep(20);
- runningSnapshot = await adapter.getBackgroundTask(result.task.taskId);
- }
- expect(Number.isInteger(launcherPid), JSON.stringify(runningSnapshot)).toBe(true);
- expect(Number.isInteger(workerPid), JSON.stringify(runningSnapshot)).toBe(true);
- expect(Number.isInteger(runningSnapshot?.pid)).toBe(true);
- expect(readPosixProcessGroupId(launcherPid)).not.toBe(
- readPosixProcessGroupId(runningSnapshot!.pid!),
- );
- expect(isProcessAlive(launcherPid)).toBe(true);
- expect(isProcessAlive(workerPid)).toBe(true);
- await adapter.cancelBackgroundTask(result.task.taskId);
- let launcherStillRunning = true;
- let workerStillRunning = true;
- for (let attempt = 0; attempt < 120; attempt += 1) {
- launcherStillRunning = isProcessAlive(launcherPid);
- workerStillRunning = isProcessAlive(workerPid);
- if (!launcherStillRunning && !workerStillRunning) break;
- await sleep(25);
- }
- expect(launcherStillRunning).toBe(false);
- expect(workerStillRunning).toBe(false);
- let terminalSnapshot = await adapter.getBackgroundTask(result.task.taskId);
- for (let attempt = 0; attempt < 100 && !terminalSnapshot?.result; attempt += 1) {
- await sleep(20);
- terminalSnapshot = await adapter.getBackgroundTask(result.task.taskId);
- }
- expect(terminalSnapshot).toMatchObject({
- status: "cancelled",
- result: { status: "cancelled" },
- });
- } finally {
- if (Number.isInteger(workerPid) && workerPid > 0 && isProcessAlive(workerPid)) {
- process.kill(workerPid, "SIGKILL");
- }
- if (Number.isInteger(launcherPid) && launcherPid > 0 && isProcessAlive(launcherPid)) {
- process.kill(launcherPid, "SIGKILL");
- }
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(process.platform === "win32")(
- "keeps Bash descendant enumeration out of generic argv cancellation",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-generic-group-stop-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- let workerPid = Number.NaN;
- const workerScript = "setInterval(() => {}, 10_000);";
- const launcherScript = [
- "const { spawn } = require('node:child_process');",
- `const worker = spawn(process.execPath, ['-e', ${JSON.stringify(workerScript)}], { detached: true, stdio: ['ignore', 'inherit', 'inherit'] });`,
- "process.stdout.write('worker:' + worker.pid + '\\n');",
- "worker.unref();",
- "setInterval(() => {}, 10_000);",
- ].join("");
- try {
- const started = await adapter.start({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", launcherScript],
- },
- });
- let runningSnapshot = await adapter.getBackgroundTask(started.taskId);
- for (let attempt = 0; attempt < 100; attempt += 1) {
- workerPid = Number(/worker:(\d+)/u.exec(runningSnapshot?.stdoutTail ?? "")?.[1]);
- if (Number.isInteger(workerPid) && workerPid > 0) break;
- await sleep(20);
- runningSnapshot = await adapter.getBackgroundTask(started.taskId);
- }
- expect(Number.isInteger(workerPid), JSON.stringify(runningSnapshot)).toBe(true);
- expect(readPosixProcessGroupId(workerPid)).not.toBe(
- readPosixProcessGroupId(runningSnapshot!.pid!),
- );
- await adapter.cancelBackgroundTask(started.taskId);
- // Bug 根因:PPID 后代枚举属于 Bash runtime;通用 ExecutionPort 必须保留
- // 原有的进程组停止边界,不能顺带获得新的跨 PGID kill 能力。
- await sleep(850);
- expect(isProcessAlive(workerPid)).toBe(true);
- } finally {
- if (Number.isInteger(workerPid) && workerPid > 0 && isProcessAlive(workerPid)) {
- process.kill(workerPid, "SIGKILL");
- }
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it("cancels an explicit lifecycle task when the adapter closes", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-close-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('unexpected'), 10_000)"],
- },
- timeoutMs: 5,
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- await adapter.close();
- const snapshot = await capable.getBackgroundTask(result.task.taskId);
- expect(snapshot?.status).toBe("cancelled");
- expect(snapshot?.result?.status).toBe("cancelled");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("cancels before background commit when the parent is already aborted", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-pre-abort-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const parentTurn = new AbortController();
- parentTurn.abort();
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('unexpected'), 30)"],
- },
- timeoutMs: 5,
- trace: {
- sessionId: "exec-explicit-background-pre-abort-session",
- attributes: { toolCallId: "toolu_explicit_background_pre_abort" },
- } as any,
- },
- { mode: "explicit" },
- { signal: parentTurn.signal },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.status).toBe("cancelled");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("returns an explicit spawn failure without publishing a background task", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-explicit-background-spawn-fail-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: join(root, "missing-executable"),
- },
- timeoutMs: 5,
- trace: {
- sessionId: "exec-explicit-background-spawn-fail-session",
- attributes: { toolCallId: "toolu_explicit_background_spawn_fail" },
- } as any,
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.status).toBe("spawn_error");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("settles completion, timeout, and abort boundary races exactly once", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-races-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const backgroundTaskIds = new Set<string>();
- try {
- for (let attempt = 0; attempt < 12; attempt++) {
- const parentTurn = new AbortController();
- let outcomeCount = 0;
- let forwardedTerminalEvents = 0;
- const childDelayMs = attempt % 3 === 2 ? 5 : 12;
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- `setTimeout(() => process.stdout.write('race-${attempt}'), ${childDelayMs})`,
- ],
- },
- timeoutMs: 5,
- trace: {
- sessionId: `exec-background-race-${attempt}`,
- attributes: { toolCallId: `toolu_background_race_${attempt}` },
- } as any,
- },
- { mode: "auto_on_timeout" },
- {
- signal: parentTurn.signal,
- onEvent: (event) => {
- if (event.type === "completed" || event.type === "failed") {
- forwardedTerminalEvents += 1;
- }
- if (event.type === "started" && attempt % 3 === 0) {
- queueMicrotask(() => parentTurn.abort());
- } else if (event.type === "started" && attempt % 3 === 2) {
- setTimeout(() => parentTurn.abort(), 5);
- }
- },
- },
- ).then((outcome) => {
- outcomeCount += 1;
- return outcome;
- });
- if (result.kind === "backgrounded") {
- expect(backgroundTaskIds.has(result.task.taskId)).toBe(false);
- backgroundTaskIds.add(result.task.taskId);
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- } else {
- expect(["cancelled", "completed"]).toContain(result.result.status);
- }
- await sleep(5);
- expect(outcomeCount).toBe(1);
- expect(forwardedTerminalEvents).toBeLessThanOrEqual(1);
- }
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("stops forwarding foreground progress after auto-backgrounding", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-progress-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- progressIntervalMs: 5,
- progressThresholdMs: 1,
- });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const progressEvents: ExecutionEvent[] = [];
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- [
- "let writes = 0;",
- "const timer = setInterval(() => {",
- " process.stdout.write(String(writes));",
- " writes += 1;",
- " if (writes >= 8) { clearInterval(timer); process.exit(0); }",
- "}, 20);",
- ].join(""),
- ],
- },
- timeoutMs: 25,
- outputLimit: {
- persistOutput: "always",
- },
- trace: {
- sessionId: "exec-auto-background-progress-session",
- attributes: {
- toolCallId: "toolu_auto_background_progress",
- },
- } as any,
- },
- { mode: "auto_on_timeout" },
- {
- onEvent: (event) => {
- if (event.type === "progress") progressEvents.push(event);
- },
- },
- );
- expect(result.kind).toBe("backgrounded");
- const forwardedProgressAfterBackground = progressEvents.length;
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- expect(progressEvents).toHaveLength(forwardedProgressAfterBackground);
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("resolves failed snapshots for auto-backgrounded foreground commands", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-fail-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- "setTimeout(() => { process.stderr.write('boom'); process.exit(7); }, 60)",
- ],
- },
- timeoutMs: 10,
- outputLimit: {
- persistOutput: "always",
- },
- trace: {
- sessionId: "exec-auto-background-fail-session",
- attributes: {
- toolCallId: "toolu_auto_background_fail",
- },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("backgrounded");
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("failed");
- expect(snapshot?.result?.exitCode).toBe(7);
- expect(snapshot?.result?.stderr.text).toBe("boom");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("keeps foreground results foreground when commands finish before timeout", async () => {
- const adapter = new NodeExecutionAdapter();
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('ok')"],
- },
- timeoutMs: 1_000,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.status).toBe("completed");
- expect(result.result.stdout.text).toBe("ok");
- } finally {
- await adapter.close();
- }
- });
- it("removes auto-background output artifacts when foreground completion wins", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-cleanup-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const stdoutPath = join(root, "cleanup-session", "cleanup-tool-stdout.log");
- const stderrPath = join(root, "cleanup-session", "cleanup-tool-stderr.log");
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('ok')"],
- },
- timeoutMs: 1_000,
- trace: {
- sessionId: "cleanup-session",
- attributes: {
- toolCallId: "cleanup-tool",
- },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.stdout.artifactPath).toBeUndefined();
- expect(result.result.stderr.artifactPath).toBeUndefined();
- await expect(readFile(stdoutPath, "utf8")).rejects.toMatchObject({
- code: "ENOENT",
- });
- await expect(readFile(stderrPath, "utf8")).rejects.toMatchObject({
- code: "ENOENT",
- });
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("settles foreground completion when redundant artifact cleanup fails", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-foreground-cleanup-failure-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const stdoutPath = join(root, "cleanup-failure-session", "cleanup-failure-tool-stdout.log");
- const retainedFile = join(stdoutPath, "retained.log");
- vi.spyOn(adapter, "run").mockImplementation(async (_request, options) => {
- await options?.onEvent?.({
- type: "started",
- pid: 123,
- timestamp: new Date(0),
- });
- await unlink(stdoutPath);
- await mkdir(stdoutPath);
- await writeFile(retainedFile, "cleanup failed");
- return {
- status: "completed",
- exitCode: 0,
- stdout: {
- text: "ok",
- bytes: 2,
- truncated: false,
- artifactBytes: 2,
- artifactPath: stdoutPath,
- artifactTruncated: false,
- },
- stderr: { text: "", bytes: 0, truncated: false },
- durationMs: 1,
- timedOut: false,
- cancelled: false,
- startedAt: new Date(0),
- completedAt: new Date(1),
- };
- });
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: { mode: "argv", file: process.execPath },
- timeoutMs: 1_000,
- trace: {
- sessionId: "cleanup-failure-session",
- attributes: { toolCallId: "cleanup-failure-tool" },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.stdout.artifactPath).toBeUndefined();
- expect(result.result.stdout.artifactBytes).toBeUndefined();
- await expect(readFile(retainedFile, "utf8")).resolves.toBe("cleanup failed");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("settles foreground completion with honest metadata when artifact truncation fails", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-foreground-truncate-failure-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const stdoutPath = join(root, "truncate-failure-session", "truncate-failure-tool-stdout.log");
- const retainedFile = join(stdoutPath, "retained.log");
- vi.spyOn(adapter, "run").mockImplementation(async (_request, options) => {
- await options?.onEvent?.({
- type: "started",
- pid: 123,
- timestamp: new Date(0),
- });
- await unlink(stdoutPath);
- await mkdir(stdoutPath);
- await writeFile(retainedFile, "not truncated");
- return {
- status: "completed",
- exitCode: 0,
- stdout: {
- text: "ok",
- bytes: 2,
- truncated: false,
- artifactBytes: 13,
- artifactPath: stdoutPath,
- artifactTruncated: false,
- },
- stderr: { text: "", bytes: 0, truncated: false },
- durationMs: 1,
- timedOut: false,
- cancelled: false,
- startedAt: new Date(0),
- completedAt: new Date(1),
- };
- });
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: { mode: "argv", file: process.execPath },
- timeoutMs: 1_000,
- outputLimit: {
- maxPersistedBytes: 4,
- persistOutput: "always",
- },
- trace: {
- sessionId: "truncate-failure-session",
- attributes: { toolCallId: "truncate-failure-tool" },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.stdout).toMatchObject({
- artifactBytes: 13,
- artifactPath: stdoutPath,
- artifactTruncated: false,
- });
- await expect(readFile(retainedFile, "utf8")).resolves.toBe("not truncated");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("keeps explicitly requested foreground output artifacts when foreground completion wins", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-preserve-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const stdoutPath = join(root, "preserve-session", "preserve-tool-stdout.log");
- const stderrPath = join(root, "preserve-session", "preserve-tool-stderr.log");
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('ok')"],
- },
- timeoutMs: 1_000,
- outputLimit: {
- persistOutput: "always",
- },
- trace: {
- sessionId: "preserve-session",
- attributes: {
- toolCallId: "preserve-tool",
- },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.stdout.artifactPath).toBe(stdoutPath);
- await expect(readFile(stdoutPath, "utf8")).resolves.toBe("ok");
- await expect(readFile(stderrPath, "utf8")).rejects.toMatchObject({
- code: "ENOENT",
- });
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("does not stop auto-backgrounded commands at the foreground persisted output limit", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-auto-background-limit-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- [
- "let writes = 0;",
- "const timer = setInterval(() => {",
- " process.stdout.write('x'.repeat(512));",
- " writes += 1;",
- " if (writes >= 200) { clearInterval(timer); process.exit(0); }",
- "}, 1);",
- ].join(""),
- ],
- },
- timeoutMs: 20,
- outputLimit: {
- maxInlineBytes: 0,
- maxPersistedBytes: 1_024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "limit-session",
- attributes: {
- toolCallId: "limit-tool",
- },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("backgrounded");
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.error).toBeUndefined();
- expect(snapshot?.result?.exitCode).toBe(0);
- expect(snapshot?.result?.stdout.artifactBytes).toBeGreaterThan(1_024);
- expect(snapshot?.result?.stdout.artifactTruncated).toBe(false);
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH)(
- "stops foreground Bash at the periodic soft limit and removes its oversized file",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-hard-cap-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- progressIntervalMs: 10,
- });
- const outputLimit = 1_024;
- try {
- const result = await adapter.run(
- {
- command: {
- mode: "shell",
- command: `${JSON.stringify(process.execPath)} -e ${JSON.stringify("process.stdout.write('x'.repeat(4096)); setInterval(() => {}, 1000)")}`,
- shellProfile: "posix-bash",
- shellOverride: POSIX_BASH_PATH,
- },
- timeoutMs: 0,
- outputLimit: {
- maxInlineBytes: 0,
- maxPersistedBytes: outputLimit,
- persistOutput: "always",
- },
- },
- {
- onPersistedLimit: () => undefined,
- shouldStopOnPersistedLimit: () => true,
- } as ExecutionRunOptions & {
- onPersistedLimit: () => void;
- shouldStopOnPersistedLimit: () => boolean;
- },
- );
- expect(result).toMatchObject({
- status: "cancelled",
- exitCode: 137,
- cancelled: true,
- error: { type: "output_limit" },
- stdout: {
- bytes: 4096,
- },
- });
- expect(result.stdout.artifactPath).toBeUndefined();
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- 15_000,
- );
- it("applies the shared 5GiB watchdog policy after Bash background commit", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-watchdog-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- let capturedRequest: ExecutionRequest | undefined;
- let sharesPersistedLimitAcrossStreams = false;
- let shouldStopOnPersistedLimit = false;
- const runSpy = vi.spyOn(adapter, "run").mockImplementation(async (request, options) => {
- capturedRequest = request;
- const internalOptions = options as ExecutionRunOptions & {
- sharePersistedOutputLimitAcrossStreams?: boolean;
- shouldStopOnPersistedLimit?: () => boolean;
- };
- await options?.onEvent?.({
- type: "started",
- pid: 123,
- timestamp: new Date(0),
- });
- shouldStopOnPersistedLimit = internalOptions.shouldStopOnPersistedLimit?.() === true;
- sharesPersistedLimitAcrossStreams =
- internalOptions.sharePersistedOutputLimitAcrossStreams === true;
- return {
- status: "completed",
- exitCode: 0,
- stdout: { text: "", bytes: 0, truncated: false },
- stderr: { text: "", bytes: 0, truncated: false },
- durationMs: 1,
- timedOut: false,
- cancelled: false,
- startedAt: new Date(0),
- completedAt: new Date(1),
- };
- });
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: { mode: "argv", file: process.execPath },
- timeoutMs: 5,
- outputLimit: {
- killProcessOnPersistedLimit: true,
- maxPersistedBytes: 1_024,
- persistOutput: "on_truncate",
- },
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- expect(capturedRequest?.timeoutMs).toBe(0);
- expect(capturedRequest?.outputLimit).toMatchObject({
- killProcessOnPersistedLimit: false,
- maxPersistedBytes: 5 * 1024 * 1024 * 1024,
- persistOutput: "always",
- });
- expect(sharesPersistedLimitAcrossStreams).toBe(true);
- expect(shouldStopOnPersistedLimit).toBe(true);
- expect(runSpy).toHaveBeenCalledTimes(1);
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it("normalizes a background Bash output-limit stop to killed exit 137 semantics", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-limit-result-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- vi.spyOn(adapter, "run").mockImplementation(async (_request, options) => {
- const internalOptions = options as ExecutionRunOptions & {
- onPersistedLimit?: () => void;
- };
- await options?.onEvent?.({
- type: "started",
- pid: 123,
- timestamp: new Date(0),
- });
- internalOptions.onPersistedLimit?.();
- return {
- status: "failed",
- exitCode: 0,
- stdout: {
- text: "",
- bytes: 5 * 1024 * 1024 * 1024 + 1,
- truncated: true,
- },
- stderr: { text: "", bytes: 0, truncated: false },
- durationMs: 1,
- timedOut: false,
- cancelled: false,
- startedAt: new Date(0),
- completedAt: new Date(1),
- };
- });
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: { mode: "argv", file: process.execPath },
- outputLimit: { persistOutput: "always" },
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.result).toMatchObject({
- status: "cancelled",
- cancelled: true,
- timedOut: false,
- exitCode: 137,
- error: {
- type: "output_limit",
- message: "Background command killed: output file exceeded 5GB",
- },
- });
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH)(
- "does not apply the runtime soft limit before its first check and retains the full foreground file",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-final-limit-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- progressIntervalMs: 60_000,
- });
- let persistedLimitNotified = false;
- try {
- const result = await adapter.run(
- {
- command: {
- mode: "shell",
- command: "printf abc",
- shellProfile: "posix-bash",
- shellOverride: POSIX_BASH_PATH,
- },
- timeoutMs: 0,
- outputLimit: {
- maxInlineBytes: 1,
- maxPersistedBytes: 2,
- maxArtifactBytes: 1,
- persistOutput: "on_truncate",
- },
- },
- {
- onPersistedLimit: () => {
- persistedLimitNotified = true;
- },
- shouldStopOnPersistedLimit: () => false,
- } as ExecutionRunOptions & {
- onPersistedLimit: () => void;
- shouldStopOnPersistedLimit: () => boolean;
- },
- );
- expect(result).toMatchObject({
- status: "completed",
- exitCode: 0,
- timedOut: false,
- cancelled: false,
- stdout: {
- bytes: 3,
- text: "a",
- artifactBytes: 3,
- artifactTruncated: false,
- },
- });
- expect(result.error).toBeUndefined();
- expect(persistedLimitNotified).toBe(false);
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abc");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "ignores the legacy Bash artifact cap after lifecycle completion",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-lifecycle-artifact-cap-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "printf abc",
- shellProfile: "posix-bash",
- shellOverride: POSIX_BASH_PATH,
- },
- timeoutMs: 1_000,
- outputLimit: {
- maxInlineBytes: 0,
- maxPersistedBytes: 100,
- maxArtifactBytes: 1,
- persistOutput: "always",
- },
- trace: {
- sessionId: "lifecycle-artifact-cap-session",
- attributes: { toolCallId: "lifecycle-artifact-cap-tool" },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result).toMatchObject({
- status: "completed",
- stdout: {
- bytes: 3,
- artifactBytes: 3,
- artifactTruncated: false,
- },
- });
- await expect(readFile(result.result.stdout.artifactPath!, "utf8")).resolves.toBe("abc");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "stops watching at root exit even when descendants later exceed the soft limit",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-retained-output-limit-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- progressIntervalMs: 10,
- progressThresholdMs: 0,
- });
- try {
- const result = await adapter.run(
- {
- command: {
- mode: "shell",
- command: "(sleep 0.05; printf 0123456789; sleep 1) & printf x",
- shellProfile: "posix-bash",
- shellOverride: POSIX_BASH_PATH,
- },
- timeoutMs: 0,
- outputLimit: {
- killProcessOnPersistedLimit: true,
- maxInlineBytes: 30_000,
- maxPersistedBytes: 3,
- persistOutput: "always",
- },
- },
- {
- shouldRetainExecutionAfterRootExit: () => true,
- } as ExecutionRunOptions & {
- shouldRetainExecutionAfterRootExit: () => boolean;
- },
- );
- expect(result.status).toBe("completed");
- expect(result.error).toBeUndefined();
- expect(result.stdout.text).toBe("x");
- await sleep(1_200);
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("x0123456789");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it("runs argv commands without a shell and streams output events", async () => {
- const adapter = new NodeExecutionAdapter();
- const events: ExecutionEvent[] = [];
- const result = await adapter.run(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('ok')"],
- },
- },
- {
- onEvent: (event) => {
- events.push(event);
- },
- },
- );
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("ok");
- expect(events[0]?.type).toBe("started");
- expect(events.some((event) => event.type === "stdout")).toBe(true);
- expect(events.at(-1)?.type).toBe("completed");
- });
- it("captures final cwd for successful foreground shell commands when requested", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-cwd-"));
- const child = join(root, " child with spaces ");
- await mkdir(child);
- try {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: `cd ${JSON.stringify(child)}`,
- },
- cwd: root,
- captureCwdAfterSuccess: true,
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.resolvedCwd).toBe(await realpath(child));
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- });
- it.skipIf(process.platform !== "win32")(
- "captures final cwd for Windows cmd shell commands when requested",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-win-cwd-"));
- const child = join(root, "child");
- await mkdir(child);
- try {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: `cd /d "${child}"`,
- },
- cwd: root,
- captureCwdAfterSuccess: true,
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.resolvedCwd).toBe(await realpath(child));
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it("does not capture cwd for generic shell commands by default", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-cwd-default-"));
- const child = join(root, "child");
- await mkdir(child);
- try {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: `cd ${JSON.stringify(child)}`,
- },
- cwd: root,
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.resolvedCwd).toBeUndefined();
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- });
- it("does not capture cwd when the shell command exits non-zero", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-cwd-fail-"));
- const child = join(root, "child");
- await mkdir(child);
- try {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: `cd ${JSON.stringify(child)}; false`,
- },
- cwd: root,
- captureCwdAfterSuccess: true,
- });
- expect(result.status).toBe("failed");
- expect(result.exitCode).toBe(1);
- expect(result.resolvedCwd).toBeUndefined();
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH)(
- "runs posix-bash shell profile commands with bash/zsh syntax",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-posix-bash-"));
- const home = join(root, "home");
- await mkdir(home, { recursive: true });
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "cat <(printf ok)",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("ok");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "creates shell init snapshots with login shell and runs user commands without login",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-login-mode-"));
- const home = join(root, "home");
- const bin = join(root, "bin");
- const shellLog = join(root, "shell-args.log");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(home, { recursive: true });
- await mkdir(bin, { recursive: true });
- await writeFile(
- shellWrapper,
- [
- "#!/usr/bin/env bash",
- 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
- "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
- `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
- "",
- ].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: shellWrapper,
- ZCODE_TEST_SHELL_LOG: shellLog,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: 'shopt -q login_shell; rc=$?; printf "%s" "$rc"',
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("1");
- const invocations = (await readFile(shellLog, "utf8")).trim().split("\n");
- expect(invocations[0]).toContain("-c -l");
- expect(invocations.at(-1)).toMatch(/^-c /u);
- expect(invocations.at(-1)).not.toContain("-l ");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "injects embedded search prelude into posix-bash shell profile commands",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-embedded-search-"));
- const home = join(root, "home");
- await mkdir(home, { recursive: true });
- const shimScript = [
- "if (process.argv[1] !== 'grep') process.exit(11);",
- "process.stdout.write(`shim:${process.argv.slice(2).join('|')}`);",
- ].join("");
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "grep needle file.txt",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- bashPrelude: {
- kind: "embedded-search",
- backend: {
- kind: "internal-cli",
- command: process.execPath,
- args: ["-e", shimScript],
- },
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("shim:needle|file.txt");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "falls back to native grep when embedded search backend is unavailable and preserves stdin",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-embedded-search-fallback-"));
- const home = join(root, "home");
- await mkdir(home, { recursive: true });
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "printf 'before\\nneedle from stdin\\nafter\\n' | grep needle",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- bashPrelude: {
- kind: "embedded-search",
- backend: {
- kind: "internal-cli",
- command: join(root, "missing-zcode"),
- args: ["__internal-search"],
- },
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("needle from stdin\n");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "sources shell init snapshot and skips login for the user command after creation",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-integration-"));
- const home = join(root, "home");
- const bin = join(root, "bin");
- const shellLog = join(root, "shell-args.log");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(home, { recursive: true });
- await mkdir(bin, { recursive: true });
- await writeFile(
- join(home, ".bashrc"),
- "alias zcode_snapshot_alias='printf alias-from-snapshot'\n",
- );
- await writeFile(
- shellWrapper,
- [
- "#!/usr/bin/env bash",
- 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
- "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
- `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
- "",
- ].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: shellWrapper,
- ZCODE_TEST_SHELL_LOG: shellLog,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "zcode_snapshot_alias",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("alias-from-snapshot");
- const log = await readFile(shellLog, "utf8");
- const invocations = log.trim().split("\n");
- expect(invocations[0]).toContain("-c -l");
- expect(invocations.at(-1)).toMatch(/^-c /u);
- expect(invocations.at(-1)).not.toContain("-l ");
- const snapshotSessionDir = join(root, "shell-snapshots");
- const beforeClose = await readdir(snapshotSessionDir);
- expect(beforeClose.some((file) => file.endsWith(".sh"))).toBe(true);
- await adapter.close();
- const afterClose = await readdir(snapshotSessionDir).catch((error: unknown) => {
- if (
- typeof error === "object" &&
- error !== null &&
- "code" in error &&
- error.code === "ENOENT"
- ) {
- return [];
- }
- throw error;
- });
- expect(afterClose).toEqual([]);
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "creates shell init snapshots with the resolved shell environment",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-env-"));
- const home = join(root, "home");
- const bin = join(root, "bin");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(home, { recursive: true });
- await mkdir(bin, { recursive: true });
- await writeFile(
- join(home, ".bashrc"),
- [
- 'if [ "$SHELL" = "$ZCODE_EXPECTED_SHELL" ] && [ "$GIT_EDITOR" = "true" ]; then',
- " alias zcode_env_overlay_alias='printf env-overlay-ok'",
- "fi",
- "",
- ].join("\n"),
- );
- await writeFile(
- shellWrapper,
- ["#!/usr/bin/env bash", `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`, ""].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- GIT_EDITOR: "stale-editor",
- HOME: home,
- SHELL: "/bin/fish",
- ZCODE_EXPECTED_SHELL: shellWrapper,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "zcode_env_overlay_alias",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("env-overlay-ok");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "falls back to login shell when a cached shell init snapshot file is missing",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-missing-"));
- const home = join(root, "home");
- const bin = join(root, "bin");
- const shellLog = join(root, "shell-args.log");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(home, { recursive: true });
- await mkdir(bin, { recursive: true });
- await writeFile(
- join(home, ".bashrc"),
- "alias zcode_snapshot_alias='printf alias-from-snapshot'\n",
- );
- await writeFile(
- shellWrapper,
- [
- "#!/usr/bin/env bash",
- 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
- "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
- `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
- "",
- ].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: shellWrapper,
- ZCODE_TEST_SHELL_LOG: shellLog,
- },
- });
- const first = await adapter.run({
- command: {
- mode: "shell",
- command: "zcode_snapshot_alias",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- });
- expect(first.status).toBe("completed");
- expect(first.stdout.text).toBe("alias-from-snapshot");
- const snapshotSessionDir = join(root, "shell-snapshots");
- const snapshotFiles = await readdir(snapshotSessionDir);
- const snapshotFile = snapshotFiles.find((file) => file.endsWith(".sh"));
- expect(snapshotFile).toBeDefined();
- await unlink(join(snapshotSessionDir, snapshotFile!));
- const second = await adapter.run({
- command: {
- mode: "shell",
- command: "printf second-ok",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- });
- expect(second.status).toBe("completed");
- expect(second.stdout.text).toBe("second-ok");
- const invocations = (await readFile(shellLog, "utf8")).trim().split("\n");
- expect(invocations[0]).toContain("-c -l");
- expect(invocations[1]).toMatch(/^-c /u);
- expect(invocations[1]).not.toContain("-l ");
- expect(invocations[2]).toContain("-c -l");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "does not spawn the user command when closing during shell init snapshot creation",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-close-"));
- const bin = join(root, "bin");
- const shellLog = join(root, "shell-args.log");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(bin, { recursive: true });
- await writeFile(
- shellWrapper,
- [
- "#!/usr/bin/env bash",
- 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
- "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
- "if [ \"$1\" = '-c' ] && [ \"$2\" = '-l' ] && printf '%s' \"$3\" | grep -q 'SNAPSHOT_FILE='; then",
- " sleep 0.2",
- "fi",
- `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
- "",
- ].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- SHELL: shellWrapper,
- ZCODE_TEST_SHELL_LOG: shellLog,
- },
- });
- const runPromise = adapter.run({
- command: {
- mode: "shell",
- command: "printf user-command-ran",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- });
- await sleep(50);
- await adapter.close();
- const result = await runPromise;
- expect(result.status).toBe("cancelled");
- expect(result.stdout.text).toBe("");
- const invocations = (await readFile(shellLog, "utf8")).trim().split("\n");
- expect(invocations).toHaveLength(1);
- expect(invocations[0]).toContain("-c -l");
- expect(invocations[0]).toContain("SNAPSHOT_FILE=");
- const snapshotSessionDir = join(root, "shell-snapshots");
- const snapshotsAfterClose = await readdir(snapshotSessionDir).catch((error: unknown) => {
- if (
- typeof error === "object" &&
- error !== null &&
- "code" in error &&
- error.code === "ENOENT"
- ) {
- return [];
- }
- throw error;
- });
- expect(snapshotsAfterClose).toEqual([]);
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "does not spawn the user command when aborted during shell init snapshot creation",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-abort-"));
- const bin = join(root, "bin");
- const shellLog = join(root, "shell-args.log");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(bin, { recursive: true });
- await writeFile(
- shellWrapper,
- [
- "#!/usr/bin/env bash",
- 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
- "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
- "if [ \"$1\" = '-c' ] && [ \"$2\" = '-l' ] && printf '%s' \"$3\" | grep -q 'SNAPSHOT_FILE='; then",
- " sleep 0.2",
- "fi",
- `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
- "",
- ].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- SHELL: shellWrapper,
- ZCODE_TEST_SHELL_LOG: shellLog,
- },
- });
- const controller = new AbortController();
- const runPromise = adapter.run(
- {
- command: {
- mode: "shell",
- command: "printf user-command-ran",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- },
- { signal: controller.signal },
- );
- await sleep(50);
- controller.abort();
- const result = await runPromise;
- expect(result.status).toBe("cancelled");
- expect(result.stdout.text).toBe("");
- const invocations = (await readFile(shellLog, "utf8")).trim().split("\n");
- expect(invocations).toHaveLength(1);
- expect(invocations[0]).toContain("-c -l");
- expect(invocations[0]).toContain("SNAPSHOT_FILE=");
- await adapter.close();
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "falls back to login shell when shell init snapshot creation fails",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-fallback-"));
- const bin = join(root, "bin");
- const shellLog = join(root, "shell-args.log");
- const shellWrapper = join(bin, "bash-wrapper");
- await mkdir(bin, { recursive: true });
- await writeFile(
- shellWrapper,
- [
- "#!/usr/bin/env bash",
- 'printf \'%q \' "$@" >> "$ZCODE_TEST_SHELL_LOG"',
- "printf '\\n' >> \"$ZCODE_TEST_SHELL_LOG\"",
- "if [ \"$1\" = '-c' ] && [ \"$2\" = '-l' ] && printf '%s' \"$3\" | grep -q 'SNAPSHOT_FILE='; then",
- " exit 42",
- "fi",
- `exec ${JSON.stringify(POSIX_BASH_PATH!)} "$@"`,
- "",
- ].join("\n"),
- { mode: 0o755 },
- );
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- SHELL: shellWrapper,
- ZCODE_TEST_SHELL_LOG: shellLog,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "printf fallback-ok",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: shellWrapper,
- source: "auto-detected",
- },
- },
- trace: {
- sessionId: "shell-init-session",
- },
- });
- expect(result.status).toBe("completed");
- expect(result.stdout.text).toBe("fallback-ok");
- const log = await readFile(shellLog, "utf8");
- const invocations = log.trim().split("\n");
- expect(invocations[0]).toContain("-c -l");
- expect(invocations.at(-1)).toContain("-c -l");
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "keeps cwd capture after shell init snapshot source commands",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-shell-init-cwd-"));
- const home = join(root, "home");
- const child = join(root, "child");
- await mkdir(home, { recursive: true });
- await mkdir(child, { recursive: true });
- await writeFile(join(home, ".bashrc"), 'zcode_cd_child() { cd "$ZCODE_TEST_CHILD"; }\n');
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- ZCODE_TEST_CHILD: child,
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "zcode_cd_child",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- captureCwdAfterSuccess: true,
- cwd: root,
- trace: {
- sessionId: "shell-init-session",
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.resolvedCwd).toBe(await realpath(child));
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "runs posix-bash shell profile commands with bash-specific syntax when bash is the user shell",
- async () => {
- const adapter = new NodeExecutionAdapter({
- processEnv: {
- ...process.env,
- SHELL: POSIX_BASH_PATH ?? "/bin/bash",
- },
- });
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: [
- "arr=(a b)",
- "printf '%s\\n' \"${arr[1]}\"",
- "false | true",
- "printf '%s\\n' \"${PIPESTATUS[0]} ${PIPESTATUS[1]}\"",
- "[[ -n x ]] && printf '%s\\n' ok",
- ].join("\n"),
- shellProfile: "posix-bash",
- },
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe("b\n1 0\nok\n");
- },
- );
- it.skipIf(process.platform !== "win32" || !WINDOWS_GIT_BASH_PATH)(
- "runs Bash syntax through Git Bash on Windows",
- async () => {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "shell",
- shellProfile: "posix-bash",
- command: [
- "arr=(a b)",
- "printf 'array=%s\\n' \"${arr[1]}\"",
- "cat <(printf process)",
- ].join("\n"),
- },
- captureCwdAfterSuccess: true,
- timeoutMs: 5000,
- });
- expect(result.status).toBe("completed");
- expect(result.stdout.text).toContain("array=b");
- expect(result.stdout.text).toContain("process");
- },
- );
- it.skipIf(process.platform !== "win32" || !WINDOWS_GIT_BASH_PATH)(
- "writes Windows Git Bash stdout and stderr directly to one canonical output",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-git-bash-merged-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- shellProfile: "posix-bash",
- command:
- "printf 'stdout-1\\n'; sleep 0.05; printf 'stderr-1\\n' >&2; sleep 0.05; printf 'stdout-2\\n'",
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "git-bash-merged-session",
- attributes: { toolCallId: "git-bash-merged-tool" },
- } as any,
- });
- const outputPath = join(
- outputRootDir,
- "git-bash-merged-session",
- "git-bash-merged-tool-stdout.log",
- );
- expect(result.status).toBe("completed");
- expect(result.stdout.text).toBe("stdout-1\nstderr-1\nstdout-2\n");
- expect(result.stderr).toEqual({ text: "", bytes: 0, truncated: false });
- expect(result.stdout.artifactPath).toBe(outputPath);
- await expect(readFile(outputPath, "utf8")).resolves.toBe(result.stdout.text);
- await expect(
- stat(join(outputRootDir, "git-bash-merged-session", "git-bash-merged-tool-stderr.log")),
- ).rejects.toMatchObject({ code: "ENOENT" });
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it("creates a cmd-compatible cwd capture wrapper for Windows shell commands", () => {
- const windowsPlan = createCwdCapturePlan(
- {
- command: {
- mode: "shell",
- command: "cd C:\\repo",
- },
- captureCwdAfterSuccess: true,
- },
- { dialect: "cmd", platform: "win32" },
- );
- expect(windowsPlan.cwdFilePath).toBeDefined();
- expect(windowsPlan.command).toMatchObject({
- mode: "shell",
- });
- expect(windowsPlan.command.command).toContain("cd C:\\repo");
- expect(windowsPlan.command.command).toContain('set "__zcode_status=%ERRORLEVEL%"');
- expect(windowsPlan.command.command).toContain('if "%__zcode_status%"=="0" cd > "');
- expect(windowsPlan.command.command).toContain("exit /b %__zcode_status%");
- });
- it("does not create a cwd capture wrapper for argv commands", () => {
- const argvPlan = createCwdCapturePlan(
- {
- command: {
- mode: "argv",
- file: "pwd",
- },
- captureCwdAfterSuccess: true,
- },
- { dialect: "posix", platform: "darwin" },
- );
- expect(argvPlan).toEqual({
- command: {
- mode: "argv",
- file: "pwd",
- },
- });
- });
- it("preserves shell profile when creating a cwd capture wrapper", () => {
- const plan = createCwdCapturePlan(
- {
- command: {
- mode: "shell",
- command: "pwd",
- shellProfile: "posix-bash",
- },
- captureCwdAfterSuccess: true,
- },
- { dialect: "posix", platform: "linux" },
- );
- expect(plan.command.mode).toBe("shell");
- if (plan.command.mode === "shell") {
- expect(plan.command.shellProfile).toBe("posix-bash");
- expect(plan.command.command).toContain("pwd");
- expect(plan.command.command).toContain("__zcode_status=$?");
- }
- });
- it("uses POSIX cwd capture syntax for Windows Git Bash", () => {
- const plan = createCwdCapturePlan(
- {
- command: {
- mode: "shell",
- command: "cd subdir",
- shellProfile: "posix-bash",
- },
- captureCwdAfterSuccess: true,
- },
- { dialect: "git-bash", platform: "win32" },
- );
- expect(plan.command.mode).toBe("shell");
- if (plan.command.mode === "shell") {
- expect(plan.command.command).toContain("__zcode_status=$?");
- expect(plan.command.command).toContain("pwd -P >");
- expect(plan.command.command).not.toContain("%ERRORLEVEL%");
- }
- });
- it("normalizes captured Git Bash cwd back to a Windows host path", () => {
- expect(normalizeCapturedCwdForHost("/c/path/to/repo", "git-bash")).toBe("C:\\path\\to\\repo");
- expect(normalizeCapturedCwdForHost("C:\\path\\to\\repo", "cmd")).toBe("C:\\path\\to\\repo");
- });
- it("emits progress events with elapsed time, byte counts, and tail output", async () => {
- const adapter = new NodeExecutionAdapter({
- progressIntervalMs: 5,
- progressThresholdMs: 1,
- });
- const events: ExecutionEvent[] = [];
- const result = await adapter.run(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- "process.stdout.write('first'); setTimeout(() => process.stdout.write('second'), 30); setTimeout(() => {}, 70)",
- ],
- },
- },
- {
- onEvent: (event) => {
- events.push(event);
- },
- },
- );
- const progress = events.find(
- (event): event is Extract<ExecutionEvent, { type: "progress" }> =>
- event.type === "progress" && event.stdoutBytes > 0,
- );
- expect(result.status).toBe("completed");
- expect(progress).toBeDefined();
- expect(progress?.elapsedMs).toBeGreaterThan(0);
- expect(progress?.stdoutBytes).toBeGreaterThan(0);
- expect(progress?.stdoutTail).toContain("first");
- });
- it("applies cwd and env overlay through spawn options", async () => {
- const adapter = new NodeExecutionAdapter();
- const cwd = await realpath(await mkdtemp(join(tmpdir(), "zcode-exec-")));
- const previousUnsetValue = process.env.ZCODE_EXEC_UNSET;
- process.env.ZCODE_EXEC_UNSET = "remove-me";
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- [
- "process.stdout.write(JSON.stringify({",
- "cwd: process.cwd(),",
- "value: process.env.ZCODE_EXEC_TEST,",
- "unset: process.env.ZCODE_EXEC_UNSET ?? null",
- "}))",
- ].join(""),
- ],
- },
- cwd,
- env: {
- base: "inherit",
- set: {
- ZCODE_EXEC_TEST: "yes",
- },
- unset: ["ZCODE_EXEC_UNSET"],
- },
- });
- const parsed = JSON.parse(result.stdout.text) as {
- cwd: string;
- value?: string;
- unset: string | null;
- };
- expect(result.status).toBe("completed");
- expect(parsed.cwd).toBe(cwd);
- expect(parsed.value).toBe("yes");
- expect(parsed.unset).toBeNull();
- } finally {
- if (previousUnsetValue === undefined) {
- delete process.env.ZCODE_EXEC_UNSET;
- } else {
- process.env.ZCODE_EXEC_UNSET = previousUnsetValue;
- }
- await rm(cwd, { force: true, recursive: true });
- }
- });
- it("deduplicates Windows environment keys when applying overlays", () => {
- const env = buildExecutionEnv(
- {
- base: "inherit",
- set: {
- PATH: "C:\\next-bin",
- },
- unset: ["temp"],
- },
- {
- platform: "win32",
- processEnv: {
- Path: "C:\\base-bin",
- TEMP: "C:\\Temp",
- ZCODE_KEEP: "yes",
- },
- },
- );
- expect(env.PATH).toBe("C:\\next-bin");
- expect(env.Path).toBeUndefined();
- expect(env.TEMP).toBeUndefined();
- expect(env.ZCODE_KEEP).toBe("yes");
- });
- it("injects configured network egress variables for subprocesses", () => {
- const env = buildExecutionEnv(
- {
- base: "empty",
- },
- {
- network: {
- caCertFile: "/tmp/zcode-ca.pem",
- httpProxy: "127.0.0.1:8888",
- noProxy: "localhost,127.0.0.1",
- },
- platform: "linux",
- processEnv: {
- HTTP_PROXY: "http://shell-proxy:8080",
- NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
- },
- },
- );
- expect(env.HTTP_PROXY).toBe("http://127.0.0.1:8888");
- expect(env.HTTPS_PROXY).toBe("http://127.0.0.1:8888");
- expect(env.ALL_PROXY).toBe("http://127.0.0.1:8888");
- expect(env.http_proxy).toBe("http://127.0.0.1:8888");
- expect(env.https_proxy).toBe("http://127.0.0.1:8888");
- expect(env.all_proxy).toBe("http://127.0.0.1:8888");
- expect(env.NO_PROXY).toBe("localhost,127.0.0.1");
- expect(env.no_proxy).toBe("localhost,127.0.0.1");
- expect(env.NODE_EXTRA_CA_CERTS).toBe("/tmp/zcode-ca.pem");
- expect(env.SSL_CERT_FILE).toBe("/tmp/zcode-ca.pem");
- expect(env.REQUESTS_CA_BUNDLE).toBe("/tmp/zcode-ca.pem");
- expect(env.CURL_CA_BUNDLE).toBe("/tmp/zcode-ca.pem");
- expect(env.GIT_SSL_CAINFO).toBe("/tmp/zcode-ca.pem");
- });
- it("ignores ambient standard proxy and CA env for subprocesses", () => {
- const env = buildExecutionEnv(undefined, {
- network: {},
- platform: "linux",
- processEnv: {
- NODE_ENV: "development",
- http_proxy: "http://shell-proxy:8080",
- NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
- no_proxy: ".example.test",
- PATH: "/usr/bin:/bin",
- },
- });
- expect(env.NODE_ENV).toBeUndefined();
- expect(env.HTTP_PROXY).toBeUndefined();
- expect(env.http_proxy).toBeUndefined();
- expect(env.NO_PROXY).toBeUndefined();
- expect(env.no_proxy).toBeUndefined();
- expect(env.NODE_EXTRA_CA_CERTS).toBeUndefined();
- expect(env.SSL_CERT_FILE).toBeUndefined();
- expect(env.REQUESTS_CA_BUNDLE).toBeUndefined();
- expect(env.CURL_CA_BUNDLE).toBeUndefined();
- expect(env.GIT_SSL_CAINFO).toBeUndefined();
- expect(env.PATH).toBe("/usr/bin:/bin");
- });
- it("restores captured user proxy and CA env for inherited subprocesses", () => {
- const env = buildExecutionEnv(undefined, {
- network: {},
- platform: "linux",
- processEnv: {
- [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
- NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
- http_proxy: "http://shell-proxy:8080",
- no_proxy: ".example.test",
- npm_config_proxy: "http://npm-proxy:8080",
- }),
- NODE_ENV: "development",
- PATH: "/usr/bin:/bin",
- },
- });
- expect(env.NODE_ENV).toBeUndefined();
- expect(env[ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]).toBeUndefined();
- expect(env.HTTP_PROXY).toBeUndefined();
- expect(env.http_proxy).toBe("http://shell-proxy:8080");
- expect(env.NO_PROXY).toBeUndefined();
- expect(env.no_proxy).toBe(".example.test");
- expect(env.NODE_EXTRA_CA_CERTS).toBe("/tmp/shell-ca.pem");
- expect(env.npm_config_proxy).toBe("http://npm-proxy:8080");
- expect(env.PATH).toBe("/usr/bin:/bin");
- });
- it("does not restore captured user env when command base is empty", () => {
- const env = buildExecutionEnv(
- {
- base: "empty",
- },
- {
- network: {},
- platform: "linux",
- processEnv: {
- [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
- HTTP_PROXY: "http://shell-proxy:8080",
- NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
- }),
- },
- },
- );
- expect(env[ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]).toBeUndefined();
- expect(env.HTTP_PROXY).toBeUndefined();
- expect(env.NODE_EXTRA_CA_CERTS).toBeUndefined();
- });
- it("derives subprocess proxy and CA env from explicit ZCode runtime keys", () => {
- const env = buildExecutionEnv(
- {
- base: "empty",
- },
- {
- network: {},
- platform: "linux",
- processEnv: {
- ZCODE_AGENT_CA_CERT: "/tmp/zcode-ca.pem",
- ZCODE_HTTP_PROXY: "127.0.0.1:8888",
- [ZCODE_NO_PROXY_ENV_KEY]: "localhost,127.0.0.1",
- },
- },
- );
- expect(env.HTTP_PROXY).toBe("http://127.0.0.1:8888");
- expect(env.http_proxy).toBe("http://127.0.0.1:8888");
- expect(env.NO_PROXY).toBe("localhost,127.0.0.1");
- expect(env.no_proxy).toBe("localhost,127.0.0.1");
- expect(env.NODE_EXTRA_CA_CERTS).toBe("/tmp/zcode-ca.pem");
- expect(env.SSL_CERT_FILE).toBe("/tmp/zcode-ca.pem");
- expect(env.REQUESTS_CA_BUNDLE).toBe("/tmp/zcode-ca.pem");
- expect(env.CURL_CA_BUNDLE).toBe("/tmp/zcode-ca.pem");
- expect(env.GIT_SSL_CAINFO).toBe("/tmp/zcode-ca.pem");
- });
- it("lets per-command env overlays override injected network env", () => {
- const env = buildExecutionEnv(
- {
- base: "empty",
- set: {
- HTTP_PROXY: "http://command-proxy:8080",
- },
- unset: ["SSL_CERT_FILE"],
- },
- {
- network: {
- caCertFile: "/tmp/zcode-ca.pem",
- httpProxy: "http://zcode-proxy:8080",
- },
- platform: "linux",
- processEnv: {},
- },
- );
- expect(env.HTTP_PROXY).toBe("http://command-proxy:8080");
- expect(env.HTTPS_PROXY).toBe("http://zcode-proxy:8080");
- expect(env.SSL_CERT_FILE).toBeUndefined();
- expect(env.NODE_EXTRA_CA_CERTS).toBe("/tmp/zcode-ca.pem");
- });
- it("adds a UTF-8 locale for subprocess text output when the parent locale is C", () => {
- const env = buildExecutionEnv(undefined, {
- platform: "darwin",
- processEnv: {
- LANG: "C",
- LC_ALL: "",
- LC_CTYPE: "POSIX",
- PATH: "/usr/bin:/bin",
- },
- });
- expect(env.LANG).toBe("en_US.UTF-8");
- expect(env.LC_ALL).toBe("en_US.UTF-8");
- expect(env.LC_CTYPE).toBe("en_US.UTF-8");
- expect(env.PYTHONIOENCODING).toBe("utf-8");
- expect(env.PYTHONUTF8).toBe("1");
- });
- it.skipIf(process.platform === "win32")(
- "keeps unicode path text from POSIX tools even when the parent locale is C",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-cn-"));
- const dir = join(root, "草稿");
- const file = join(dir, "file.txt");
- await mkdir(dir, { recursive: true });
- await writeFile(file, "a\nb\n");
- const adapter = new NodeExecutionAdapter({
- processEnv: {
- ...process.env,
- LANG: "C",
- LC_ALL: "",
- LC_CTYPE: "C",
- },
- });
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: "wc",
- args: ["-l", file],
- },
- });
- expect(result.status).toBe("completed");
- expect(result.stdout.text).toContain("草稿");
- expect(result.stdout.text).not.toContain("??");
- } finally {
- await rm(root, { force: true, recursive: true });
- }
- },
- );
- it("decodes Windows legacy Chinese output without corrupting UTF-8 output", () => {
- const legacy = iconv.encode("草稿", "gb18030");
- const westernLegacy = iconv.encode("é", "cp1252");
- const utf8 = Buffer.from("草稿", "utf8");
- expect(decodeExecutionOutputBuffer(legacy, "gb18030")).toBe("草稿");
- expect(decodeExecutionOutputBuffer(westernLegacy, "cp1252")).toBe("é");
- expect(decodeExecutionOutputBuffer(utf8, "gb18030")).toBe("草稿");
- });
- it.skipIf(!POSIX_BASH_PATH)("can rewrite posix-bash commands without -l", async () => {
- const command = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo before",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- {
- env: process.env,
- platform: process.platform,
- },
- );
- expect(command.args).toEqual(["-c", "-l", "echo before"]);
- const withoutLogin = setResolvedShellLoginMode(command, false);
- expect(withoutLogin.args).toEqual(["-c", "echo before"]);
- const rewritten = applyResolvedShellCommandForTest(withoutLogin, "echo after");
- expect(rewritten.args).toEqual(["-c", "echo after"]);
- });
- it("resolves Windows .cmd argv commands through cmd.exe", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "argv",
- file: "pnpm",
- args: ["--version"],
- },
- {
- cwd: "C:\\repo",
- env: {
- ComSpec: "C:\\Windows\\System32\\cmd.exe",
- Path: "C:\\tools;C:\\other",
- PATHEXT: ".COM;.EXE;.BAT;.CMD",
- },
- exists: (path) => path === "C:\\tools\\pnpm.cmd",
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: ["/d", "/s", "/c", "C:\\tools\\pnpm.cmd --version"],
- cwdDialect: "cmd",
- file: "C:\\Windows\\System32\\cmd.exe",
- shell: false,
- });
- });
- it("quotes Windows .cmd argv arguments without requiring git-bash", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "argv",
- file: "pnpm",
- args: ["run", "say hi", "A&B", "100%done", "caret^value", "pipe|value"],
- },
- {
- cwd: "C:\\repo",
- env: {
- ComSpec: "C:\\Windows\\System32\\cmd.exe",
- Path: "C:\\Program Files\\node tools",
- PATHEXT: ".COM;.EXE;.BAT;.CMD",
- },
- exists: (path) => path === "C:\\Program Files\\node tools\\pnpm.cmd",
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [
- "/d",
- "/s",
- "/c",
- '"C:\\Program Files\\node tools\\pnpm.cmd" run "say hi" "A^&B" "100^%done" "caret^^value" "pipe^|value"',
- ],
- cwdDialect: "cmd",
- file: "C:\\Windows\\System32\\cmd.exe",
- shell: false,
- });
- });
- it("resolves a Windows command from a quoted PATH entry", async () => {
- const resolved = await resolveExecutionCommand(
- { mode: "argv", file: "pnpm", args: ["install"] },
- {
- cwd: "C:\\repo",
- env: {
- ComSpec: "C:\\Windows\\System32\\cmd.exe",
- Path: '"C:\\Program Files\\node tools";C:\\Windows',
- PATHEXT: ".COM;.EXE;.BAT;.CMD",
- },
- exists: (path) => path === "C:\\Program Files\\node tools\\pnpm.cmd",
- platform: "win32",
- },
- );
- expect(resolved.args.at(-1)).toBe('"C:\\Program Files\\node tools\\pnpm.cmd" install');
- });
- it("keeps Windows .exe argv commands shell-free after PATH resolution", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "argv",
- file: "tool",
- args: ["run"],
- },
- {
- env: {
- PATH: "C:\\tools",
- PATHEXT: ".EXE;.CMD",
- },
- exists: (path) => path === "C:\\tools\\tool.exe",
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: ["run"],
- cwdDialect: "cmd",
- file: "C:\\tools\\tool.exe",
- shell: false,
- });
- });
- it("uses ComSpec as the default Windows shell", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "dir",
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- },
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: "dir",
- shell: "C:\\Windows\\System32\\cmd.exe",
- });
- });
- it("keeps generic Windows shell commands on the legacy shell path", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "dir",
- shellOverride: {
- dialect: "git-bash",
- id: "git-bash:C:\\Program Files\\Git\\bin\\bash.exe",
- label: "Git Bash",
- path: "C:\\Program Files\\Git\\bin\\bash.exe",
- source: "user-config",
- },
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- SHELL: "C:\\Program Files\\Git\\bin\\bash.exe",
- },
- exists: () => {
- throw new Error("Git Bash resolver should not run without shellProfile");
- },
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: "dir",
- shell: "C:\\Windows\\System32\\cmd.exe",
- });
- });
- it("keeps generic POSIX shell commands on the legacy Node shell path", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- },
- {
- env: {
- PATH: "/bin:/usr/bin",
- SHELL: "/bin/bash",
- },
- exists: () => {
- throw new Error("posix shell resolver should not run without shellProfile");
- },
- platform: "linux",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "posix",
- file: "echo ok",
- shell: true,
- });
- });
- it("uses a valid user-configured Windows Git Bash override before auto detection", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "printf 'ok\\n'",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "git-bash",
- id: "git-bash:D:\\Tools\\Git\\bin\\bash.exe",
- label: "Git Bash",
- path: "D:\\Tools\\Git\\bin\\bash.exe",
- source: "user-config",
- },
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\Windows\\System32",
- },
- exists: (path) =>
- path === "D:\\Tools\\Git\\bin\\bash.exe" ||
- path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toMatchObject({
- args: ["-c", "-l", expect.any(String)],
- cwdDialect: "git-bash",
- file: "D:\\Tools\\Git\\bin\\bash.exe",
- shell: false,
- });
- });
- it("falls back to auto detection when the user-configured shell no longer exists", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "printf 'ok\\n'",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "git-bash",
- id: "git-bash:D:\\Missing\\bash.exe",
- label: "Git Bash",
- path: "D:\\Missing\\bash.exe",
- source: "user-config",
- },
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\Windows\\System32",
- },
- exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toMatchObject({
- cwdDialect: "git-bash",
- file: "C:\\Program Files\\Git\\bin\\bash.exe",
- shell: false,
- });
- });
- it("resolves Windows Git Bash from the default Program Files path for posix-bash", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "printf 'ok\\n'",
- shellProfile: "posix-bash",
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\Windows\\System32",
- },
- exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toMatchObject({
- args: ["-c", "-l", expect.any(String)],
- cwdDialect: "git-bash",
- file: "C:\\Program Files\\Git\\bin\\bash.exe",
- shell: false,
- });
- });
- it("resolves Windows Git Bash from git.exe on PATH", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "printf 'ok\\n'",
- shellProfile: "posix-bash",
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "D:\\Apps\\Git\\cmd",
- },
- exists: (path) =>
- path === "D:\\Apps\\Git\\cmd\\git.exe" || path === "D:\\Apps\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toMatchObject({
- args: ["-c", "-l", expect.any(String)],
- cwdDialect: "git-bash",
- file: "D:\\Apps\\Git\\bin\\bash.exe",
- shell: false,
- });
- });
- it("uses a valid user-configured Windows cmd override before auto detection", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "dir",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "cmd",
- id: "cmd:C:\\Windows\\System32\\cmd.exe",
- label: "CMD",
- path: "C:\\Windows\\System32\\cmd.exe",
- source: "user-config",
- },
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\Windows\\System32",
- },
- exists: (path) =>
- path === "C:\\Windows\\System32\\cmd.exe" ||
- path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: "dir",
- shell: "C:\\Windows\\System32\\cmd.exe",
- });
- });
- it("uses the cmd.exe fallback override before auto Git Bash detection", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "dir",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "cmd",
- id: "cmd:cmd.exe",
- label: "CMD",
- path: "cmd.exe",
- source: "user-config",
- },
- },
- {
- env: {
- PATH: "C:\\Program Files\\Git\\cmd",
- },
- exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: "dir",
- shell: "cmd.exe",
- });
- });
- it("falls back to ComSpec when Windows Git Bash cannot be resolved", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "dir",
- shellProfile: "posix-bash",
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\tools",
- SHELL: "C:\\Program Files\\Git\\bin\\bash.exe",
- },
- exists: () => false,
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: "dir",
- shell: "C:\\Windows\\System32\\cmd.exe",
- });
- });
- it("keeps CMD parentheses and metacharacters unchanged in the Bash fallback", async () => {
- const command = "if exist input.txt (echo yes) else (echo no) & echo done";
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command,
- shellProfile: "posix-bash",
- },
- {
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\tools",
- },
- exists: () => false,
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: command,
- shell: "C:\\Windows\\System32\\cmd.exe",
- });
- });
- it("converts Windows and Git Bash paths in both directions", () => {
- expect(windowsPathToGitBashPath("C:\\repo\\sub")).toBe("/c/repo/sub");
- expect(windowsPathToGitBashPath("C:/repo/sub")).toBe("/c/repo/sub");
- expect(windowsPathToGitBashPath("C:repo\\sub")).toBe("C:repo/sub");
- expect(windowsPathToGitBashPath("\\\\server\\share\\repo")).toBe("//server/share/repo");
- expect(gitBashPathToWindowsPath("/c/repo/sub")).toBe("C:\\repo\\sub");
- expect(gitBashPathToWindowsPath("/cygdrive/d/repo")).toBe("D:\\repo");
- expect(gitBashPathToWindowsPath("//server/share/repo")).toBe("\\\\server\\share\\repo");
- });
- it.skipIf(process.platform === "win32")(
- "resolves posix-bash shell commands through bash without Node shell wrapping",
- async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "/custom/bin",
- SHELL: "/bin/bash",
- },
- exists: (path) => path === "/bin/bash",
- platform: "linux",
- },
- );
- expect(resolved).toEqual({
- args: ["-c", "-l", "echo ok"],
- cwdDialect: "posix",
- envOverlay: {
- GIT_EDITOR: "true",
- SHELL: "/bin/bash",
- },
- file: "/bin/bash",
- shell: false,
- usesLoginShell: true,
- });
- },
- );
- it.skipIf(process.platform === "win32")(
- "prefers zsh for posix-bash shell commands when the user shell is not bash",
- async () => {
- const resolution = await resolveEffectiveBashShellSelection({
- env: {
- PATH: "/zsh/bin:/bash/bin",
- SHELL: "/bin/fish",
- },
- exists: (path) => path === "/zsh/bin/zsh" || path === "/bash/bin/bash",
- platform: "darwin",
- });
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "/zsh/bin:/bash/bin",
- SHELL: "/bin/fish",
- },
- exists: (path) => path === "/zsh/bin/zsh" || path === "/bash/bin/bash",
- platform: "darwin",
- },
- );
- expect(resolution.selection).toMatchObject({
- dialect: "posix",
- display: { name: "zsh" },
- path: "/zsh/bin/zsh",
- source: "auto-detected",
- });
- expect(resolution.provider?.file).toBe("/zsh/bin/zsh");
- expect(resolved.file).toBe("/zsh/bin/zsh");
- expect(resolved.args).toEqual(["-c", "-l", "echo ok"]);
- expect(resolved.shell).toBe(false);
- expect(resolved.envOverlay).toMatchObject({
- SHELL: "/zsh/bin/zsh",
- });
- },
- );
- it.skipIf(process.platform === "win32")(
- "falls back to fixed POSIX shell directories for posix-bash commands",
- async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "/custom/bin",
- SHELL: "/bin/fish",
- },
- exists: (path) => path === "/usr/bin/bash",
- platform: "linux",
- },
- );
- expect(resolved).toMatchObject({
- args: ["-c", "-l", "echo ok"],
- file: "/usr/bin/bash",
- shell: false,
- });
- },
- );
- it.skipIf(process.platform === "win32")(
- "uses the provided auto-detected shell snapshot instead of re-detecting POSIX shells",
- async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- shellOverride: {
- dialect: "posix",
- display: { name: "zsh" },
- id: "auto:zsh",
- label: "zsh",
- path: "/snapshot/bin/zsh",
- source: "auto-detected",
- },
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "/current/bin",
- SHELL: "/bin/fish",
- },
- exists: (path) => path === "/current/bin/bash",
- platform: "linux",
- },
- );
- expect(resolved).toMatchObject({
- args: ["-c", "-l", "echo ok"],
- file: "/snapshot/bin/zsh",
- shell: false,
- });
- },
- );
- it.skipIf(process.platform === "win32")(
- "falls back to the legacy shell command when posix-bash cannot resolve bash or zsh",
- async () => {
- const resolution = await resolveEffectiveBashShellSelection({
- env: {
- PATH: "/no-shells",
- SHELL: "/bin/fish",
- },
- exists: () => false,
- platform: "linux",
- });
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "/no-shells",
- SHELL: "/bin/fish",
- },
- exists: () => false,
- platform: "linux",
- },
- );
- expect(resolution.selection).toMatchObject({
- dialect: "legacy-shell",
- display: { name: "system shell" },
- source: "legacy-fallback",
- });
- expect(resolution.provider).toBeUndefined();
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "posix",
- file: "echo ok",
- shell: true,
- });
- },
- );
- it.skipIf(process.platform === "win32")(
- "preserves a legacy shell snapshot instead of re-detecting POSIX shells",
- async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "echo ok",
- shellOverride: {
- dialect: "legacy-shell",
- display: { name: "system shell" },
- source: "legacy-fallback",
- },
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "/current/bin",
- SHELL: "/bin/fish",
- },
- exists: (path) => path === "/current/bin/bash",
- platform: "linux",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "posix",
- file: "echo ok",
- shell: true,
- });
- },
- );
- it("describes auto-detected Windows Git Bash as the effective Bash shell", async () => {
- const resolution = await resolveEffectiveBashShellSelection({
- env: {
- PATH: "",
- },
- exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- });
- expect(resolution.selection).toMatchObject({
- dialect: "git-bash",
- display: { name: "Git Bash" },
- path: "C:\\Program Files\\Git\\bin\\bash.exe",
- source: "auto-detected",
- });
- expect(resolution.provider).toMatchObject({
- dialect: "git-bash",
- file: "C:\\Program Files\\Git\\bin\\bash.exe",
- shell: false,
- });
- });
- it("describes the Windows fallback without Git Bash as CMD on ComSpec", async () => {
- const resolution = await resolveEffectiveBashShellSelection({
- env: {
- COMSPEC: "C:\\Windows\\System32\\cmd.exe",
- PATH: "C:\\tools",
- },
- exists: () => false,
- platform: "win32",
- });
- expect(resolution.selection).toEqual({
- dialect: "cmd",
- display: { name: "cmd.exe" },
- id: "auto:cmd",
- label: "cmd.exe",
- path: "C:\\Windows\\System32\\cmd.exe",
- source: "auto-detected",
- });
- expect(resolution.provider).toMatchObject({
- dialect: "cmd",
- file: "C:\\Windows\\System32\\cmd.exe",
- shell: "C:\\Windows\\System32\\cmd.exe",
- });
- });
- it("uses bare cmd.exe for the Windows fallback when ComSpec is missing", async () => {
- const resolution = await resolveEffectiveBashShellSelection({
- env: { PATH: "" },
- exists: () => false,
- platform: "win32",
- });
- const resolved = await resolveExecutionCommand(
- { mode: "shell", command: "dir", shellProfile: "posix-bash" },
- { env: { PATH: "" }, exists: () => false, platform: "win32" },
- );
- expect(resolution.selection).toMatchObject({
- dialect: "cmd",
- display: { name: "cmd.exe" },
- path: "cmd.exe",
- });
- expect(resolved).toEqual({ args: [], cwdDialect: "cmd", file: "dir", shell: "cmd.exe" });
- });
- it("uses the auto-detected Windows CMD snapshot instead of re-reading ComSpec", async () => {
- // 子代理与每次 Bash 调用都把 runtime selection 作为 shellOverride 传入,这是 Windows 回落的主路径。
- const { selection } = await resolveEffectiveBashShellSelection({
- env: { ComSpec: "C:\\Windows\\System32\\cmd.exe", PATH: "" },
- exists: () => false,
- platform: "win32",
- });
- const resolved = await resolveExecutionCommand(
- { mode: "shell", command: "dir", shellOverride: selection, shellProfile: "posix-bash" },
- {
- env: { ComSpec: "D:\\other\\cmd.exe", PATH: "" },
- exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toEqual({
- args: [],
- cwdDialect: "cmd",
- file: "dir",
- shell: "C:\\Windows\\System32\\cmd.exe",
- });
- });
- it("uses the provided auto-detected Windows Git Bash snapshot instead of re-detecting", async () => {
- const resolved = await resolveExecutionCommand(
- {
- mode: "shell",
- command: "pwd",
- shellOverride: {
- dialect: "git-bash",
- display: { name: "Git Bash" },
- id: "auto:git-bash",
- label: "Git Bash",
- path: "D:\\Git\\bin\\bash.exe",
- source: "auto-detected",
- },
- shellProfile: "posix-bash",
- },
- {
- env: {
- PATH: "",
- },
- exists: (path) => path === "C:\\Program Files\\Git\\bin\\bash.exe",
- platform: "win32",
- },
- );
- expect(resolved).toMatchObject({
- args: ["-c", "-l", "pwd"],
- file: "D:\\Git\\bin\\bash.exe",
- shell: false,
- });
- });
- it("keeps explicit Windows CMD selection ahead of auto-detected Git Bash", async () => {
- const resolution = await resolveEffectiveBashShellSelection({
- env: {
- PATH: "",
- },
- exists: (path) => path === "cmd.exe" || path === "C:\\Program Files\\Git\\bin\\bash.exe",
- override: {
- dialect: "cmd",
- display: { name: "CMD" },
- id: "cmd",
- label: "CMD",
- path: "cmd.exe",
- source: "user-config",
- },
- platform: "win32",
- });
- expect(resolution.selection).toMatchObject({
- dialect: "cmd",
- display: { name: "cmd.exe" },
- path: "cmd.exe",
- source: "user-config",
- });
- expect(resolution.provider).toMatchObject({
- dialect: "cmd",
- file: "cmd.exe",
- shell: "cmd.exe",
- });
- });
- it("returns non-zero exits as structured failed results", async () => {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stderr.write('bad'); process.exit(7)"],
- },
- });
- expect(result.status).toBe("failed");
- expect(result.exitCode).toBe(7);
- expect(result.stderr.text).toBe("bad");
- });
- it("keeps the Agent alive when a successful child closes stdin before a large write", async () => {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdin.destroy(); setTimeout(() => process.exit(0), 20);"],
- },
- stdin: "x".repeat(1024 * 1024),
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.error).toBeUndefined();
- });
- it("preserves a non-zero exit when the child closes stdin before a large write", async () => {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdin.destroy(); setTimeout(() => process.exit(7), 20);"],
- },
- stdin: "x".repeat(1024 * 1024),
- });
- expect(result.status).toBe("failed");
- expect(result.exitCode).toBe(7);
- });
- it("delivers a large stdin payload when the child consumes it", async () => {
- const adapter = new NodeExecutionAdapter();
- const stdin = "你好, ZCode!\n".repeat(100_000);
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- [
- "let bytes = 0;",
- "process.stdin.on('data', chunk => { bytes += chunk.length; });",
- "process.stdin.on('end', () => process.stdout.write(String(bytes)));",
- ].join(" "),
- ],
- },
- stdin,
- });
- expect(result.status).toBe("completed");
- expect(result.exitCode).toBe(0);
- expect(result.stdout.text).toBe(String(Buffer.byteLength(stdin)));
- });
- it("stops commands with a structured timeout result", async () => {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => {}, 5000)"],
- },
- timeoutMs: 50,
- });
- expect(result.status).toBe("timed_out");
- expect(result.timedOut).toBe(true);
- expect(result.cancelled).toBe(false);
- expect(result.error).toEqual({
- type: "timeout",
- message: "Command timed out after 50ms",
- });
- });
- it("timeout 只约束子进程运行阶段,准备较慢的命令不会未启动就被判 timed_out", async () => {
- // 回归:protected-resource sandbox 时代计时器被提前到准备阶段(覆盖 capability probe),
- // sandbox 撤除后该行为一度被保留——shell 初始化较慢或 timeout 较短时,命令还没 spawn
- // 就返回 timed_out。计时器必须在 spawn 之后才启动。
- const adapter = new NodeExecutionAdapter();
- const internals = adapter as unknown as {
- prepareChildSpawn: (request: unknown) => Promise<unknown>;
- };
- const originalPrepare = internals.prepareChildSpawn.bind(adapter);
- internals.prepareChildSpawn = async (request: unknown) => {
- await new Promise((resolve) => setTimeout(resolve, 150));
- return originalPrepare(request);
- };
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.exit(0)"],
- },
- timeoutMs: 60,
- });
- expect(result.status).toBe("completed");
- expect(result.timedOut).toBe(false);
- expect(result.exitCode).toBe(0);
- });
- it("stops commands with a structured cancellation result", async () => {
- const adapter = new NodeExecutionAdapter();
- const controller = new AbortController();
- setTimeout(() => controller.abort(), 50);
- const result = await adapter.run(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => {}, 5000)"],
- },
- },
- {
- signal: controller.signal,
- },
- );
- expect(result.status).toBe("cancelled");
- expect(result.cancelled).toBe(true);
- expect(result.timedOut).toBe(false);
- });
- it("closes running background tasks during adapter shutdown", async () => {
- const adapter = new NodeExecutionAdapter();
- const started = await adapter.start({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => {}, 10_000)"],
- },
- });
- await adapter.close();
- const snapshot = await adapter.getBackgroundTask(started.taskId);
- expect(snapshot?.status).toBe("cancelled");
- expect(snapshot?.result?.status).toBe("cancelled");
- });
- it.skipIf(process.platform === "win32")(
- "kills child processes in the same process group when shutting down",
- async () => {
- const adapter = new NodeExecutionAdapter();
- let childPidText = "";
- const script = [
- "const { spawn } = require('node:child_process');",
- "const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 10_000)'], { stdio: 'ignore' });",
- "process.stdout.write(String(child.pid));",
- "setTimeout(() => {}, 10_000);",
- ].join(" ");
- const runPromise = adapter.run(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", script],
- },
- },
- {
- onEvent: (event) => {
- if (event.type === "stdout") {
- childPidText += event.text;
- }
- },
- },
- );
- let childPid = Number.NaN;
- for (let attempt = 0; attempt < 50; attempt += 1) {
- const trimmed = childPidText.trim();
- childPid = Number(trimmed);
- if (trimmed.length > 0 && Number.isInteger(childPid) && childPid > 0) {
- break;
- }
- await sleep(20);
- }
- expect(Number.isInteger(childPid)).toBe(true);
- expect(childPid).toBeGreaterThan(0);
- await adapter.close();
- const result = await runPromise;
- expect(result.status).toBe("cancelled");
- let childStillRunning = true;
- for (let attempt = 0; attempt < 50; attempt += 1) {
- childStillRunning = isProcessAlive(childPid);
- if (!childStillRunning) {
- break;
- }
- await sleep(20);
- }
- expect(childStillRunning).toBe(false);
- },
- );
- it.skipIf(process.platform === "win32")(
- "keeps inherited-pipe descendants owned until background shutdown",
- async () => {
- const adapter = new NodeExecutionAdapter();
- let output = "";
- let descendantPid = Number.NaN;
- const descendantScript = [
- "process.on('SIGTERM', () => {});",
- "setInterval(() => {}, 10_000);",
- ].join("");
- const wrapperScript = [
- "const { spawn } = require('node:child_process');",
- `const child = spawn(process.execPath, ['-e', ${JSON.stringify(descendantScript)}], { stdio: ['ignore', 'inherit', 'inherit'] });`,
- "process.stdout.write(`descendant:${child.pid}\\n`);",
- "child.unref();",
- ].join("");
- try {
- const started = await adapter.start(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", wrapperScript],
- },
- },
- {
- onEvent: (event) => {
- if (event.type === "stdout") output += event.text;
- },
- },
- );
- for (let attempt = 0; attempt < 100; attempt += 1) {
- descendantPid = Number(/descendant:(\d+)/u.exec(output)?.[1]);
- if (Number.isInteger(descendantPid) && descendantPid > 0) break;
- await sleep(20);
- }
- expect(Number.isInteger(descendantPid)).toBe(true);
- // 超过旧实现的一秒 drain 窗口后仍应由 execution 持有,而不是伪 completed。
- await sleep(1_100);
- expect((await adapter.getBackgroundTask(started.taskId))?.status).toBe("running");
- await adapter.close();
- const snapshot = await adapter.getBackgroundTask(started.taskId);
- expect(snapshot?.status).toBe("cancelled");
- expect(snapshot?.result?.status).toBe("cancelled");
- expect(isProcessAlive(descendantPid)).toBe(false);
- } finally {
- if (Number.isInteger(descendantPid) && descendantPid > 0 && isProcessAlive(descendantPid)) {
- process.kill(descendantPid, "SIGKILL");
- }
- await adapter.close();
- }
- },
- );
- it.skipIf(process.platform === "win32")(
- "cleans inherited-pipe descendants after the foreground drain deadline",
- async () => {
- const adapter = new NodeExecutionAdapter();
- let descendantPid = Number.NaN;
- const descendantScript = "setInterval(() => {}, 10_000);";
- const wrapperScript = [
- "const { spawn } = require('node:child_process');",
- `const child = spawn(process.execPath, ['-e', ${JSON.stringify(descendantScript)}], { stdio: ['ignore', 'inherit', 'inherit'] });`,
- "process.stdout.write(`descendant:${child.pid}\\n`);",
- "child.unref();",
- ].join("");
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", wrapperScript],
- },
- });
- descendantPid = Number(/descendant:(\d+)/u.exec(result.stdout.text)?.[1]);
- expect(result.status).toBe("completed");
- expect(Number.isInteger(descendantPid)).toBe(true);
- expect(isProcessAlive(descendantPid)).toBe(false);
- } finally {
- if (Number.isInteger(descendantPid) && descendantPid > 0 && isProcessAlive(descendantPid)) {
- process.kill(descendantPid, "SIGKILL");
- }
- await adapter.close();
- }
- },
- );
- it.skipIf(process.platform === "win32")(
- "releases inherited pipes when a descendant escapes the original process group",
- async () => {
- const adapter = new NodeExecutionAdapter();
- let descendantPid = Number.NaN;
- const descendantScript = "setInterval(() => {}, 10_000);";
- const wrapperScript = [
- "const { spawn } = require('node:child_process');",
- `const child = spawn(process.execPath, ['-e', ${JSON.stringify(descendantScript)}], { detached: true, stdio: ['ignore', 'inherit', 'inherit'] });`,
- "process.stdout.write(`descendant:${child.pid}\\n`);",
- "child.unref();",
- ].join("");
- try {
- const startedAt = Date.now();
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", wrapperScript],
- },
- });
- descendantPid = Number(/descendant:(\d+)/u.exec(result.stdout.text)?.[1]);
- expect(result.status).toBe("completed");
- expect(Number.isInteger(descendantPid)).toBe(true);
- expect(Date.now() - startedAt).toBeLessThan(4_000);
- // 已脱离原 PGID 的第三方进程无法由纯 Node 可靠寻址,但不能继续用 pipe 保活 CLI。
- expect(isProcessAlive(descendantPid)).toBe(true);
- } finally {
- if (Number.isInteger(descendantPid) && descendantPid > 0 && isProcessAlive(descendantPid)) {
- process.kill(descendantPid, "SIGKILL");
- }
- await adapter.close();
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "removes a precreated Bash output file when cancelled before spawn",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-pre-spawn-cancel-"));
- const parentTurn = new AbortController();
- parentTurn.abort();
- const adapter = new NodeExecutionAdapter({ outputRootDir: root });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "printf unexpected",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "bash-pre-spawn-cancel-session",
- attributes: { toolCallId: "bash-pre-spawn-cancel-tool" },
- } as any,
- },
- { mode: "explicit" },
- { signal: parentTurn.signal },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.status).toBe("cancelled");
- await expect(
- stat(
- join(root, "bash-pre-spawn-cancel-session", "bash-pre-spawn-cancel-tool-stdout.log"),
- ),
- ).rejects.toMatchObject({ code: "ENOENT" });
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "writes Bash stdout and stderr directly to one canonical output",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-merged-"));
- const home = join(outputRootDir, "home");
- await mkdir(home, { recursive: true });
- const processEnv = {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- };
- delete processEnv.BASH_MAX_OUTPUT_LENGTH;
- const adapter = new NodeExecutionAdapter({ outputRootDir, processEnv });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command:
- "printf 'stdout-1\\n'; sleep 0.05; printf 'stderr-1\\n' >&2; sleep 0.05; printf 'stdout-2\\n'",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "bash-merged-session",
- attributes: { toolCallId: "bash-merged-tool" },
- } as any,
- });
- const outputPath = join(
- outputRootDir,
- "bash-merged-session",
- "bash-merged-tool-stdout.log",
- );
- expect(result.status).toBe("completed");
- expect(result.stdout.text).toBe("stdout-1\nstderr-1\nstdout-2\n");
- expect(result.stderr).toEqual({ text: "", bytes: 0, truncated: false });
- expect(result.stdout.artifactPath).toBe(outputPath);
- await expect(readFile(outputPath, "utf8")).resolves.toBe(result.stdout.text);
- expect((await stat(outputPath)).mode & 0o777).toBe(0o600);
- await expect(
- stat(join(outputRootDir, "bash-merged-session", "bash-merged-tool-stderr.log")),
- ).rejects.toMatchObject({ code: "ENOENT" });
- const failed = await adapter.run({
- command: {
- mode: "shell",
- command: "printf 'before\\n'; printf 'failure\\n' >&2; exit 7",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "bash-merged-session",
- attributes: { toolCallId: "bash-merged-failed-tool" },
- } as any,
- });
- expect(failed).toMatchObject({
- status: "failed",
- exitCode: 7,
- stdout: {
- text: "before\nfailure\n",
- },
- stderr: {
- text: "",
- bytes: 0,
- },
- });
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "reports filesystem diagnostics for empty failed Bash output",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-lost-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const cases = [
- {
- id: "disk-full",
- statfs: {
- bavail: 9n,
- bfree: 9n,
- blocks: 10n,
- bsize: 1024n * 1024n,
- ffree: 10_000n,
- files: 10_000n,
- type: 0n,
- },
- diagnostic: (outputDirectory: string) =>
- `Command output was lost: the temp filesystem at ${outputDirectory} is full (9MB free). The child process's stdout/stderr writes failed with ENOSPC. Free up space on this filesystem.`,
- },
- {
- id: "inode-full",
- statfs: {
- bavail: 100n,
- bfree: 100n,
- blocks: 100n,
- bsize: 1024n * 1024n,
- ffree: 999n,
- files: 10_000n,
- type: 0n,
- },
- diagnostic: (outputDirectory: string) =>
- `Command output was lost: the temp filesystem at ${outputDirectory} is out of inodes (999 free). The child process's stdout/stderr writes failed with ENOSPC. Free up space on this filesystem.`,
- },
- ];
- try {
- for (const testCase of cases) {
- statfsMock.mockResolvedValueOnce(testCase.statfs);
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "exit 7",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- timeoutMs: 5_000,
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: `bash-${testCase.id}-session`,
- attributes: { toolCallId: `bash-${testCase.id}-tool` },
- } as any,
- },
- { mode: "auto_on_timeout" },
- );
- const outputDirectory = join(outputRootDir, `bash-${testCase.id}-session`);
- expect(result.kind).toBe("foreground");
- expect(result.result).toMatchObject({
- status: "failed",
- exitCode: 7,
- stdout: {
- text: testCase.diagnostic(outputDirectory),
- },
- stderr: {
- text: "",
- bytes: 0,
- },
- });
- expect(result.result.stdout.artifactPath).toBeUndefined();
- expect(statfsMock).toHaveBeenCalledWith(outputDirectory, { bigint: true });
- }
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "retains a secure zero-byte Bash artifact when persistence is always",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-empty-artifact-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: ":",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "bash-empty-artifact-session",
- attributes: { toolCallId: "bash-empty-artifact-tool" },
- } as any,
- });
- const outputPath = join(
- outputRootDir,
- "bash-empty-artifact-session",
- "bash-empty-artifact-tool-stdout.log",
- );
- expect(result).toMatchObject({
- status: "completed",
- stdout: {
- artifactBytes: 0,
- artifactPath: outputPath,
- artifactTruncated: false,
- bytes: 0,
- text: "",
- truncated: false,
- },
- });
- await expect(readFile(outputPath, "utf8")).resolves.toBe("");
- expect((await stat(outputPath)).mode & 0o777).toBe(0o600);
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "settles Bash output preparation failures before spawning",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-prepare-"));
- const blockedSessionPath = join(outputRootDir, "blocked-session");
- await writeFile(blockedSessionPath, "not a directory");
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- const events: ExecutionEvent[] = [];
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "printf unexpected",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "blocked-session",
- attributes: { toolCallId: "blocked-tool" },
- } as any,
- },
- { mode: "auto_on_timeout" },
- {
- onEvent: (event) => {
- events.push(event);
- },
- },
- );
- expect(result.kind).toBe("foreground");
- expect(result.result.status).toBe("spawn_error");
- expect(result.result.error?.message).toContain("blocked-session");
- expect(events.some((event) => event.type === "started")).toBe(false);
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)("settles a Bash artifact open failure before spawning", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-open-"));
- const outputPath = join(outputRootDir, "open-failure-session", "open-failure-tool-stdout.log");
- await mkdir(outputPath, { recursive: true });
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "printf output",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 1,
- maxPersistedBytes: 64,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "open-failure-session",
- attributes: { toolCallId: "open-failure-tool" },
- } as any,
- });
- expect(result.status).toBe("spawn_error");
- expect(result.stdout.artifactPath).toBeUndefined();
- expect(result.stdout.bytes).toBe(0);
- expect(result.error?.message).toContain("open-failure-tool-stdout.log");
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH)("does not create a parent WriteStream for Bash output", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-write-"));
- const outputPath = join(
- outputRootDir,
- "write-failure-session",
- "write-failure-tool-stdout.log",
- );
- const probePath = join(outputRootDir, "file-handle-probe");
- const probeHandle = await open(probePath, "w");
- const fileHandlePrototype = Object.getPrototypeOf(probeHandle) as {
- createWriteStream: typeof probeHandle.createWriteStream;
- };
- await probeHandle.close();
- await unlink(probePath);
- const createWriteStreamSpy = vi.spyOn(fileHandlePrototype, "createWriteStream");
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const launch = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "printf first; sleep 0.2; printf second",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "write-failure-session",
- attributes: { toolCallId: "write-failure-tool" },
- } as any,
- },
- { mode: "explicit" },
- );
- expect(launch.kind).toBe("backgrounded");
- if (launch.kind !== "backgrounded") throw new Error("Expected background launch");
- const snapshot = await capable.waitForBackgroundTask!(launch.task.taskId);
- expect(snapshot).toMatchObject({
- outputPath,
- status: "completed",
- stdoutPersistedOutputPath: outputPath,
- });
- expect(snapshot?.result?.stdout.text).toBe("firstsecond");
- expect(snapshot?.result?.stdout.artifactPath).toBe(outputPath);
- expect(createWriteStreamSpy).not.toHaveBeenCalled();
- await expect(readFile(outputPath, "utf8")).resolves.toBe("firstsecond");
- } finally {
- createWriteStreamSpy.mockRestore();
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH || process.platform === "win32")(
- "rejects a symlinked Bash canonical output path",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-output-symlink-"));
- const sessionDir = join(outputRootDir, "symlink-session");
- const targetPath = join(outputRootDir, "target.log");
- const outputPath = join(sessionDir, "symlink-tool-stdout.log");
- await mkdir(sessionDir, { recursive: true });
- await writeFile(targetPath, "preserved");
- await symlink(targetPath, outputPath);
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "printf overwritten",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64,
- persistOutput: "always",
- },
- trace: {
- sessionId: "symlink-session",
- attributes: { toolCallId: "symlink-tool" },
- } as any,
- });
- expect(result.status).toBe("spawn_error");
- await expect(readFile(targetPath, "utf8")).resolves.toBe("preserved");
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH || process.platform === "win32")(
- "does not kill descendants when the Bash root exits normally",
- async () => {
- const adapter = new NodeExecutionAdapter();
- let descendantPid = Number.NaN;
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command:
- "(trap '' TERM HUP; while :; do sleep 10; done) & printf 'descendant:%s\\n' \"$!\"",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- });
- descendantPid = Number(/descendant:(\d+)/u.exec(result.stdout.text)?.[1]);
- expect(result.status).toBe("completed");
- expect(Number.isInteger(descendantPid)).toBe(true);
- // Bash 工具在 root 进程退出时结算,正常完成不主动清理后代;测试自行收尾。
- expect(isProcessAlive(descendantPid)).toBe(true);
- } finally {
- if (Number.isInteger(descendantPid) && descendantPid > 0 && isProcessAlive(descendantPid)) {
- process.kill(descendantPid, "SIGKILL");
- }
- await adapter.close();
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH && !WINDOWS_GIT_BASH_PATH)(
- "settles the background task at root exit before late descendant output",
- async () => {
- const bashPath = POSIX_BASH_PATH ?? WINDOWS_GIT_BASH_PATH!;
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-descendant-progress-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir,
- progressIntervalMs: 50,
- progressThresholdMs: 0,
- });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "(sleep 0.5; printf late) & printf early",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: bashPath,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "always",
- },
- trace: {
- sessionId: "bash-descendant-progress-session",
- attributes: { toolCallId: "bash-descendant-progress-tool" },
- } as any,
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- const completed = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(completed).toMatchObject({
- status: "completed",
- result: {
- stdout: {
- text: "early",
- },
- },
- });
- expect(result.task.outputPath).toBeTypeOf("string");
- await sleep(600);
- await expect(readFile(result.task.outputPath!, "utf8")).resolves.toBe("earlylate");
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it("keeps generic argv stdout and stderr separate", async () => {
- const adapter = new NodeExecutionAdapter();
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('stdout'); process.stderr.write('stderr')"],
- },
- });
- expect(result.stdout.text).toBe("stdout");
- expect(result.stderr.text).toBe("stderr");
- } finally {
- await adapter.close();
- }
- });
- it.skipIf(!POSIX_BASH_PATH)(
- "deletes redundant Bash files and keeps complete retained files without losing observed size",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-cap-"));
- const processEnv = { ...process.env };
- delete processEnv.BASH_MAX_OUTPUT_LENGTH;
- const adapter = new NodeExecutionAdapter({ outputRootDir, processEnv });
- const shellOverride = {
- dialect: "posix" as const,
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected" as const,
- };
- try {
- const smallResult = await adapter.run({
- command: {
- mode: "shell",
- command: "printf ok",
- shellProfile: "posix-bash",
- shellOverride,
- },
- outputLimit: {
- maxInlineBytes: 3,
- maxPersistedBytes: 4,
- maxArtifactBytes: 4,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "bash-cap-session",
- attributes: { toolCallId: "bash-small-tool" },
- } as any,
- });
- const smallPath = join(outputRootDir, "bash-cap-session", "bash-small-tool-stdout.log");
- expect(smallResult.stdout).toMatchObject({
- text: "ok",
- bytes: 2,
- truncated: false,
- });
- expect(smallResult.stdout.artifactPath).toBeUndefined();
- await expect(stat(smallPath)).rejects.toMatchObject({ code: "ENOENT" });
- const largeResult = await adapter.run({
- command: {
- mode: "shell",
- command: "printf abcdef",
- shellProfile: "posix-bash",
- shellOverride,
- },
- outputLimit: {
- maxInlineBytes: 3,
- maxPersistedBytes: 4,
- maxArtifactBytes: 4,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "bash-cap-session",
- attributes: { toolCallId: "bash-large-tool" },
- } as any,
- });
- expect(largeResult.stdout).toMatchObject({
- text: "abc",
- bytes: 6,
- truncated: true,
- artifactBytes: 6,
- artifactTruncated: false,
- });
- await expect(readFile(largeResult.stdout.artifactPath!, "utf8")).resolves.toBe("abcdef");
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "allows a short Bash command to finish before the first soft-limit check",
- async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-bash-limit-"));
- const processEnv = { ...process.env };
- delete processEnv.BASH_MAX_OUTPUT_LENGTH;
- const adapter = new NodeExecutionAdapter({
- outputRootDir,
- processEnv,
- progressIntervalMs: 5,
- progressThresholdMs: 0,
- });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "printf abcdef",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- timeoutMs: 5_000,
- outputLimit: {
- killProcessOnPersistedLimit: true,
- maxInlineBytes: 3,
- maxPersistedBytes: 4,
- persistOutput: "always",
- },
- trace: {
- sessionId: "bash-watchdog-session",
- attributes: { toolCallId: "bash-watchdog-tool" },
- } as any,
- });
- expect(result).toMatchObject({
- status: "completed",
- stdout: {
- text: "abc",
- bytes: 6,
- artifactBytes: 6,
- artifactTruncated: false,
- },
- });
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abcdef");
- expect(result.error).toBeUndefined();
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- },
- );
- it("parses BASH_MAX_OUTPUT_LENGTH within its documented bounds", () => {
- expect(resolveBashMaxOutputLength({}, 30_000)).toBe(30_000);
- expect(resolveBashMaxOutputLength({}, 120)).toBe(120);
- expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: " " }, 120)).toBe(30_000);
- expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "4096suffix" })).toBe(4096);
- expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "invalid" })).toBe(30_000);
- expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "0" })).toBe(30_000);
- expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "-1" })).toBe(30_000);
- expect(resolveBashMaxOutputLength({ BASH_MAX_OUTPUT_LENGTH: "200000" })).toBe(150_000);
- });
- it.skipIf(!POSIX_BASH_PATH)(
- "applies BASH_MAX_OUTPUT_LENGTH when reading the Bash output file",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-env-limit-"));
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- BASH_MAX_OUTPUT_LENGTH: "4suffix",
- },
- });
- try {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: "printf abcdef",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 100,
- maxPersistedBytes: 64,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "bash-env-limit-session",
- attributes: { toolCallId: "bash-env-limit-tool" },
- } as any,
- });
- expect(result.stdout).toMatchObject({
- text: "abcd",
- bytes: 6,
- truncated: true,
- artifactBytes: 6,
- });
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "keeps the 30000-byte Bash boundary inline and persists byte 30001",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bash-default-limit-"));
- const processEnv = { ...process.env };
- delete processEnv.BASH_MAX_OUTPUT_LENGTH;
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv,
- });
- try {
- for (const size of [30_000, 30_001]) {
- const result = await adapter.run({
- command: {
- mode: "shell",
- command: `${JSON.stringify(process.execPath)} -e "process.stdout.write('x'.repeat(${size}))"`,
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "bash-default-limit-session",
- attributes: { toolCallId: `bash-default-limit-${size}` },
- } as any,
- });
- expect(result.stdout.bytes).toBe(size);
- expect(result.stdout.text).toHaveLength(30_000);
- expect(result.stdout.truncated).toBe(size > 30_000);
- expect(result.stdout.artifactPath !== undefined).toBe(size > 30_000);
- }
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it("truncates inline output while preserving observed byte counts", async () => {
- const adapter = new NodeExecutionAdapter();
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('abcdef')"],
- },
- outputLimit: {
- maxInlineBytes: 3,
- },
- });
- expect(result.stdout.text).toBe("abc");
- expect(result.stdout.bytes).toBe(6);
- expect(result.stdout.truncated).toBe(true);
- });
- it("persists full stream output once inline output is truncated", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-output-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('abcdef')"],
- },
- outputLimit: {
- maxInlineBytes: 3,
- persistOutput: "on_truncate",
- },
- trace: {
- traceId: "trace-output" as never,
- sessionId: "session-output" as never,
- attributes: {
- toolCallId: "tool-output",
- },
- },
- });
- expect(result.stdout.text).toBe("abc");
- expect(result.stdout.truncated).toBe(true);
- expect(result.stdout.artifactPath).toBeDefined();
- expect(result.stdout.artifactBytes).toBe(6);
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abcdef");
- } finally {
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it("uses the ZCode storage root for persisted output when no output root is injected", async () => {
- const storageRoot = await mkdtemp(join(tmpdir(), "zcode-exec-storage-root-"));
- const adapter = new NodeExecutionAdapter({
- processEnv: {
- ...process.env,
- ZCODE_STORAGE_DIR: storageRoot,
- },
- });
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('abcdef')"],
- },
- outputLimit: {
- maxInlineBytes: 3,
- persistOutput: "on_truncate",
- },
- trace: {
- traceId: "trace-storage-root" as never,
- sessionId: "session-storage-root" as never,
- attributes: {
- toolCallId: "tool-storage-root",
- },
- },
- });
- expect(result.stdout.artifactPath).toBe(
- join(storageRoot, "cli", "exec", "session-storage-root", "tool-storage-root-stdout.log"),
- );
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abcdef");
- } finally {
- await rm(storageRoot, { force: true, recursive: true });
- }
- });
- it("caps persisted stream output while continuing to drain the child", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-output-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('abcdef')"],
- },
- outputLimit: {
- maxInlineBytes: 3,
- maxPersistedBytes: 4,
- persistOutput: "on_truncate",
- },
- });
- expect(result.status).toBe("completed");
- expect(result.stdout.bytes).toBe(6);
- expect(result.stdout.artifactBytes).toBe(4);
- expect(result.stdout.artifactTruncated).toBe(true);
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("abcd");
- } finally {
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it("kills the process when persisted output reaches a watchdog limit", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-output-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('x'.repeat(100)); setTimeout(() => {}, 5000)"],
- },
- timeoutMs: 5000,
- outputLimit: {
- maxInlineBytes: 0,
- maxPersistedBytes: 4,
- persistOutput: "always",
- killProcessOnPersistedLimit: true,
- },
- });
- expect(result.status).toBe("failed");
- expect(result.error?.type).toBe("output_limit");
- expect(result.stdout.bytes).toBe(100);
- expect(result.stdout.artifactBytes).toBe(4);
- expect(result.stdout.artifactTruncated).toBe(true);
- await expect(readFile(result.stdout.artifactPath!, "utf8")).resolves.toBe("xxxx");
- } finally {
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it("shares one persisted watchdog limit across stdout and stderr", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-aggregate-output-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const result = await adapter.run(
- {
- command: {
- mode: "argv",
- file: process.execPath,
- args: [
- "-e",
- "process.stdout.write('a'.repeat(8)); process.stderr.write('b'.repeat(8)); setTimeout(() => {}, 5000)",
- ],
- },
- timeoutMs: 5000,
- outputLimit: {
- maxInlineBytes: 0,
- maxPersistedBytes: 10,
- persistOutput: "always",
- killProcessOnPersistedLimit: true,
- },
- },
- {
- sharePersistedOutputLimitAcrossStreams: true,
- } as ExecutionRunOptions & {
- sharePersistedOutputLimitAcrossStreams: boolean;
- },
- );
- expect(result.status).toBe("failed");
- expect(result.error?.type).toBe("output_limit");
- expect((result.stdout.artifactBytes ?? 0) + (result.stderr.artifactBytes ?? 0)).toBe(10);
- const [stdoutArtifact, stderrArtifact] = await Promise.all([
- readFile(result.stdout.artifactPath!),
- readFile(result.stderr.artifactPath!),
- ]);
- expect(stdoutArtifact.byteLength + stderrArtifact.byteLength).toBe(10);
- } finally {
- await adapter.close();
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it("tracks background executions until completion", async () => {
- const outputRootDir = await mkdtemp(join(tmpdir(), "zcode-exec-background-"));
- const adapter = new NodeExecutionAdapter({ outputRootDir });
- try {
- const started = await adapter.start({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "setTimeout(() => process.stdout.write('bg'), 25)"],
- },
- outputLimit: {
- persistOutput: "always",
- },
- trace: {
- traceId: "trace-bg" as never,
- sessionId: "session-bg" as never,
- attributes: {
- toolCallId: "tool-bg",
- },
- },
- });
- expect(started.status).toBe("running");
- expect(started.outputPath).toBe(join(outputRootDir, "session-bg", "tool-bg-stdout.log"));
- expect(started.stdoutPersistedOutputPath).toBe(started.outputPath);
- expect(started.stderrPersistedOutputPath).toBe(
- join(outputRootDir, "session-bg", "tool-bg-stderr.log"),
- );
- await expect(readFile(started.stdoutPersistedOutputPath!, "utf8")).resolves.toBe("");
- await expect(readFile(started.stderrPersistedOutputPath!, "utf8")).resolves.toBe("");
- let snapshot = await adapter.getBackgroundTask(started.taskId);
- for (let attempt = 0; attempt < 20 && snapshot?.status === "running"; attempt++) {
- await sleep(20);
- snapshot = await adapter.getBackgroundTask(started.taskId);
- }
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.outputPath).toBe(started.outputPath);
- expect(snapshot?.stdoutPersistedOutputPath).toBe(started.stdoutPersistedOutputPath);
- expect(snapshot?.stderrPersistedOutputPath).toBe(started.stderrPersistedOutputPath);
- expect(snapshot?.result?.stdout.text).toBe("bg");
- await expect(readFile(started.stdoutPersistedOutputPath!, "utf8")).resolves.toBe("bg");
- } finally {
- await rm(outputRootDir, { force: true, recursive: true });
- }
- });
- it("does not capture cwd for background shell executions", async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-background-cwd-"));
- const child = join(root, "child");
- await mkdir(child);
- const adapter = new NodeExecutionAdapter();
- try {
- const started = await adapter.start({
- command: {
- mode: "shell",
- command: `cd ${JSON.stringify(child)}; printf bg`,
- },
- cwd: root,
- captureCwdAfterSuccess: true,
- });
- let snapshot = await adapter.getBackgroundTask(started.taskId);
- for (let attempt = 0; attempt < 20 && snapshot?.status === "running"; attempt++) {
- await sleep(20);
- snapshot = await adapter.getBackgroundTask(started.taskId);
- }
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.result?.stdout.text).toBe("bg");
- expect(snapshot?.result?.resolvedCwd).toBeUndefined();
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- });
- it.skipIf(!POSIX_BASH_PATH)(
- "runs posix-bash shell profile commands in background executions",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bg-bash-"));
- const home = join(root, "home");
- await mkdir(home, { recursive: true });
- try {
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- },
- });
- const started = await adapter.start({
- command: {
- mode: "shell",
- command: "cat <(printf bg)",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- captureCwdAfterSuccess: true,
- });
- let snapshot = await adapter.getBackgroundTask(started.taskId);
- for (let attempt = 0; attempt < 50 && snapshot?.status === "running"; attempt++) {
- await sleep(20);
- snapshot = await adapter.getBackgroundTask(started.taskId);
- }
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.result?.stdout.text).toBe("bg");
- expect(snapshot?.result?.resolvedCwd).toBeUndefined();
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it.skipIf(!POSIX_BASH_PATH)(
- "keeps one canonical Bash output file across explicit background commit",
- async () => {
- const root = await mkdtemp(join(tmpdir(), "zcode-exec-bg-bash-output-"));
- const home = join(root, "home");
- await mkdir(home, { recursive: true });
- const adapter = new NodeExecutionAdapter({
- outputRootDir: root,
- processEnv: {
- ...process.env,
- HOME: home,
- SHELL: POSIX_BASH_PATH!,
- },
- progressIntervalMs: 5,
- progressThresholdMs: 1,
- });
- const capable = adapter as BashBackgroundLifecycleCapableAdapter;
- try {
- const result = await capable.runBashWithBackgroundLifecycle!(
- {
- command: {
- mode: "shell",
- command: "printf 'out\\n'; printf 'err\\n' >&2; sleep 0.05; printf 'done\\n'",
- shellProfile: "posix-bash",
- shellOverride: {
- dialect: "posix",
- display: { name: "bash" },
- path: POSIX_BASH_PATH!,
- source: "auto-detected",
- },
- },
- outputLimit: {
- maxInlineBytes: 30_000,
- maxPersistedBytes: 64 * 1024 * 1024,
- persistOutput: "on_truncate",
- },
- trace: {
- sessionId: "bash-background-output-session",
- attributes: { toolCallId: "bash-background-output-tool" },
- } as any,
- },
- { mode: "explicit" },
- );
- expect(result.kind).toBe("backgrounded");
- expect(result.task.outputPath).toBe(result.task.stdoutPersistedOutputPath);
- expect(result.task.stderrPersistedOutputPath).toBeUndefined();
- await expect(readFile(result.task.outputPath!, "utf8")).resolves.toBeDefined();
- await vi.waitFor(async () => {
- expect(await readFile(result.task.outputPath!, "utf8")).toContain("out");
- });
- const snapshot = await capable.waitForBackgroundTask!(result.task.taskId);
- expect(snapshot?.status).toBe("completed");
- expect(snapshot?.stdoutPersistedOutputPath).toBe(result.task.outputPath);
- expect(snapshot?.stderrPersistedOutputPath).toBeUndefined();
- expect(snapshot?.result?.stdout.text).toBe("out\nerr\ndone\n");
- expect(snapshot?.result?.stderr).toEqual({
- text: "",
- bytes: 0,
- truncated: false,
- });
- await expect(readFile(result.task.outputPath!, "utf8")).resolves.toBe("out\nerr\ndone\n");
- } finally {
- await adapter.close();
- await rm(root, { recursive: true, force: true });
- }
- },
- );
- it("updates background snapshots with progress output", async () => {
- const adapter = new NodeExecutionAdapter({
- progressIntervalMs: 10,
- progressTailBytes: 128,
- progressThresholdMs: 1,
- });
- const started = await adapter.start({
- command: {
- mode: "argv",
- file: process.execPath,
- args: ["-e", "process.stdout.write('ready'); setTimeout(() => {}, 1000)"],
- },
- });
- let snapshot = await adapter.getBackgroundTask(started.taskId);
- for (let attempt = 0; attempt < 50 && snapshot?.stdoutBytes !== 5; attempt++) {
- await sleep(20);
- snapshot = await adapter.getBackgroundTask(started.taskId);
- }
- expect(snapshot?.status).toBe("running");
- expect(snapshot?.stdoutBytes).toBe(5);
- expect(snapshot?.stdoutTail).toBe("ready");
- const cancelled = await adapter.cancelBackgroundTask(started.taskId);
- expect(cancelled?.status).toBe("cancelled");
- });
- });
- describe("Windows Git Bash discovery", () => {
- const fixedBashPath = "C:\\Program Files\\Git\\bin\\bash.exe";
- const fixedX86BashPath = "C:\\Program Files (x86)\\Git\\bin\\bash.exe";
- function installationFiles(root: string): string[] {
- return [
- win32.join(root, "bin", "bash.exe"),
- win32.join(root, "cmd", "git.exe"),
- win32.join(root, "git-bash.exe"),
- ];
- }
- function discoveryFixture(
- env: NodeJS.ProcessEnv,
- executables: string[],
- textFiles: Record<string, string> = {},
- ) {
- const availablePaths = new Set(executables);
- // 回归测试必须隔离真实注册表和 Scoop 配置,避免当前机器的 Git 安装掩盖漏检。
- const isExecutable = vi.fn((path: string) => availablePaths.has(path));
- const readRegistryInstallRoots = vi.fn(async (): Promise<string[]> => []);
- const readTextFile = vi.fn(async (path: string): Promise<string> => {
- if (Object.hasOwn(textFiles, path)) return textFiles[path]!;
- throw Object.assign(new Error("Missing fixture file"), { code: "ENOENT" });
- });
- return {
- env,
- platform: "win32",
- isExecutable,
- readRegistryInstallRoots,
- readTextFile,
- };
- }
- it("keeps legacy fixed directories ahead of PATH and added installation roots", async () => {
- const customRoot = "D:\\PortableGit";
- const fixture = discoveryFixture(
- { PATH: win32.join(customRoot, "cmd"), GIT_INSTALL_ROOT: customRoot },
- [fixedBashPath, fixedX86BashPath, ...installationFiles(customRoot)],
- );
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: fixedBashPath,
- source: "system",
- });
- expect(fixture.readRegistryInstallRoots).not.toHaveBeenCalled();
- expect(fixture.readTextFile).not.toHaveBeenCalled();
- });
- it("keeps the legacy x86 fixed directory without requiring new layout markers", async () => {
- const fixture = discoveryFixture({ PATH: "" }, [fixedX86BashPath]);
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: fixedX86BashPath,
- source: "system",
- });
- });
- it.each(["PATH", "Path", "pAtH"])(
- "handles quoted PATH entries, empty entries and the %s environment key",
- async (pathKey) => {
- const root = "D:\\Git With Spaces";
- const bashPath = win32.join(root, "bin", "bash.exe");
- const fixture = discoveryFixture(
- { [pathKey]: `;;"";"${win32.join(root, "cmd")}";;`, pAtHeXt: ".EXE;.CMD" },
- [win32.join(root, "cmd", "git.exe"), bashPath],
- );
- // 原 PATH 推导只检查 Git 和 Bash,不能因新增布局校验而要求旧安装提供启动器。
- expect(await discoverWindowsGitBash(fixture)).toEqual({ path: bashPath, source: "path" });
- expect(fixture.isExecutable).not.toHaveBeenCalledWith("git.exe");
- expect(fixture.isExecutable).not.toHaveBeenCalledWith("bash.exe");
- },
- );
- it("continues after the first PATH Git has no Bash and finds the next installation", async () => {
- const root = "E:\\WorkingGit";
- const bashPath = win32.join(root, "bin", "bash.exe");
- const fixture = discoveryFixture({ PATH: `D:\\BrokenGit\\cmd;${win32.join(root, "cmd")}` }, [
- "D:\\BrokenGit\\cmd\\git.exe",
- win32.join(root, "cmd", "git.exe"),
- bashPath,
- ]);
- expect(await discoverWindowsGitBash(fixture)).toEqual({ path: bashPath, source: "path" });
- expect(fixture.isExecutable).toHaveBeenCalledWith("D:\\BrokenGit\\bin\\bash.exe");
- });
- it("keeps PATH ahead of newly discovered system installation roots", async () => {
- const pathRoot = "D:\\PathGit";
- const fixture = discoveryFixture(
- { PATH: win32.join(pathRoot, "cmd"), GIT_INSTALL_ROOT: "E:\\ConfiguredGit" },
- [...installationFiles(pathRoot), ...installationFiles("E:\\ConfiguredGit")],
- );
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(pathRoot, "bin", "bash.exe"),
- source: "path",
- });
- });
- it.each(["GIT_INSTALL_ROOT", "git_install_root"])(
- "discovers a complete installation from %s",
- async (key) => {
- const root = "E:\\CustomGit";
- const fixture = discoveryFixture({ [key]: root }, installationFiles(root));
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(root, "bin", "bash.exe"),
- source: "system",
- });
- },
- );
- it.each(["ProgramFiles", "ProgramFiles(x86)", "pRoGrAmFiLeS"])(
- "discovers Git when the system %s directory is relocated",
- async (key) => {
- const programsRoot = "E:\\System Programs";
- const root = win32.join(programsRoot, "Git");
- const fixture = discoveryFixture({ [key]: programsRoot }, installationFiles(root));
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(root, "bin", "bash.exe"),
- source: "system",
- });
- },
- );
- it("uses injected official installation roots and skips a stale installation record", async () => {
- const root = "E:\\OfficialGit";
- const fixture = discoveryFixture({}, installationFiles(root));
- fixture.readRegistryInstallRoots.mockResolvedValue(["D:\\RemovedGit", root]);
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(root, "bin", "bash.exe"),
- source: "system",
- });
- expect(fixture.readRegistryInstallRoots).toHaveBeenCalledTimes(1);
- });
- it.each([
- { label: "SCOOP user root", env: { SCOOP: "D:\\ScoopUser" }, root: "D:\\ScoopUser" },
- {
- label: "SCOOP_GLOBAL root",
- env: { SCOOP_GLOBAL: "E:\\ScoopGlobal" },
- root: "E:\\ScoopGlobal",
- },
- {
- label: "case-insensitive Scoop key",
- env: { scoop: "D:\\ScoopLower" },
- root: "D:\\ScoopLower",
- },
- {
- label: "default user root",
- env: { USERPROFILE: "D:\\Users\\dev" },
- root: "D:\\Users\\dev\\scoop",
- },
- {
- label: "explicit global root under ProgramData",
- env: { ProgramData: "E:\\ProgramData", SCOOP_GLOBAL: "E:\\ProgramData\\scoop" },
- root: "E:\\ProgramData\\scoop",
- },
- ])("discovers Scoop Git from $label", async ({ env, root }) => {
- const gitRoot = win32.join(root, "apps", "git", "current");
- const fixture = discoveryFixture(env, installationFiles(gitRoot));
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(gitRoot, "bin", "bash.exe"),
- source: "system",
- });
- });
- it.each([
- { configKey: "ROOT_PATH", location: "xdg" },
- { configKey: "GLOBAL_PATH", location: "xdg" },
- { configKey: "ROOT_PATH", location: "profile" },
- { configKey: "GLOBAL_PATH", location: "profile" },
- { configKey: "root_path", location: "xdg" },
- { configKey: "global_path", location: "profile" },
- ])(
- "reads Scoop $configKey from the $location config location",
- async ({ configKey, location }) => {
- const root = "E:\\ConfiguredScoop";
- const gitRoot = win32.join(root, "apps", "git", "current");
- const env: NodeJS.ProcessEnv = { USERPROFILE: "D:\\Users\\dev" };
- if (location === "xdg") env.XDG_CONFIG_HOME = "D:\\UserConfig";
- const configPath =
- location === "xdg"
- ? "D:\\UserConfig\\scoop\\config.json"
- : "D:\\Users\\dev\\.config\\scoop\\config.json";
- const fixture = discoveryFixture(env, installationFiles(gitRoot), {
- [configPath]: JSON.stringify({ [configKey]: root }),
- });
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(gitRoot, "bin", "bash.exe"),
- source: "system",
- });
- expect(fixture.readTextFile).toHaveBeenCalledWith(configPath);
- },
- );
- it("infers a custom Scoop root from PATH shims without Scoop environment variables", async () => {
- const root = "E:\\CustomPackageRoot";
- const gitRoot = win32.join(root, "apps", "git", "current");
- const fixture = discoveryFixture({ Path: `"${win32.join(root, "shims")}"` }, [
- win32.join(root, "shims", "git.exe"),
- ...installationFiles(gitRoot),
- ]);
- // shims 中的 Git 代理不是安装根;只用父目录线索,绝不执行代理读取目标。
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(gitRoot, "bin", "bash.exe"),
- source: "path",
- });
- });
- it.each([
- {
- label: "ChocolateyToolsLocation",
- env: { ChocolateyToolsLocation: "E:\\ChocoTools" },
- root: "E:\\ChocoTools",
- },
- {
- label: "legacy ChocolateyBinRoot",
- env: { ChocolateyBinRoot: "D:\\LegacyTools" },
- root: "D:\\LegacyTools",
- },
- {
- label: "legacy chocolatey_bin_root",
- env: { chocolatey_bin_root: "D:\\OldTools" },
- root: "D:\\OldTools",
- },
- {
- label: "explicit tools root on SystemDrive",
- env: { SystemDrive: "E:", ChocolateyToolsLocation: "E:\\tools" },
- root: "E:\\tools",
- },
- ])("discovers Chocolatey PortableGit from $label", async ({ env, root }) => {
- const gitRoot = win32.join(root, "git");
- const fixture = discoveryFixture(env, installationFiles(gitRoot));
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(gitRoot, "bin", "bash.exe"),
- source: "system",
- });
- });
- it.each([
- {
- label: "global Scoop under ProgramData",
- root: "E:\\ProgramData\\scoop\\apps\\git\\current",
- },
- { label: "portable Git under SystemDrive tools", root: "E:\\tools\\git" },
- ])("ignores an unhinted shared installation in $label", async ({ root }) => {
- const fixture = discoveryFixture(
- { USERPROFILE: "D:\\Users\\dev", ProgramData: "E:\\ProgramData", SystemDrive: "E:" },
- installationFiles(root),
- );
- // 共享目录的三文件布局可被伪造;仅知道系统目录位置不能授权自动执行其中的 Bash。
- expect(await discoverWindowsGitBash(fixture)).toBeUndefined();
- expect(fixture.isExecutable).not.toHaveBeenCalledWith(win32.join(root, "bin", "bash.exe"));
- const resolution = await resolveEffectiveBashShellSelection({
- env: fixture.env,
- platform: fixture.platform,
- exists: fixture.isExecutable,
- gitBashDiscovery: {
- readRegistryInstallRoots: fixture.readRegistryInstallRoots,
- readTextFile: fixture.readTextFile,
- },
- });
- expect(resolution.selection.dialect).toBe("cmd");
- });
- it.each(["missing", "blank", "stale", "read-failure"])(
- "does not restore shared directory defaults when installation clues are %s",
- async (kind) => {
- const env: NodeJS.ProcessEnv = {
- USERPROFILE: "D:\\Users\\dev",
- ProgramData: "E:\\ProgramData",
- SystemDrive: "E:",
- };
- if (kind === "blank") Object.assign(env, { SCOOP_GLOBAL: " ", ChocolateyToolsLocation: "" });
- if (kind === "stale") {
- Object.assign(env, {
- SCOOP_GLOBAL: "D:\\RemovedScoop",
- ChocolateyToolsLocation: "D:\\RemovedTools",
- });
- }
- const fixture = discoveryFixture(env, [
- ...installationFiles("E:\\ProgramData\\scoop\\apps\\git\\current"),
- ...installationFiles("E:\\tools\\git"),
- ]);
- if (kind === "read-failure") {
- fixture.readRegistryInstallRoots.mockRejectedValue(new Error("Registry unavailable"));
- fixture.readTextFile.mockRejectedValue(new Error("Config unavailable"));
- }
- expect(await discoverWindowsGitBash(fixture)).toBeUndefined();
- },
- );
- it.each(["scoop-config", "scoop-path", "chocolatey-path"])(
- "keeps an explicitly referenced shared installation via %s",
- async (kind) => {
- const root =
- kind === "chocolatey-path"
- ? "E:\\tools\\git"
- : "E:\\ProgramData\\scoop\\apps\\git\\current";
- const env: NodeJS.ProcessEnv = { USERPROFILE: "D:\\Users\\dev" };
- const textFiles: Record<string, string> = {};
- if (kind === "scoop-config") {
- textFiles["D:\\Users\\dev\\.config\\scoop\\config.json"] = JSON.stringify({
- GLOBAL_PATH: "E:\\ProgramData\\scoop",
- });
- } else {
- env.PATH =
- kind === "scoop-path" ? "E:\\ProgramData\\scoop\\shims" : win32.join(root, "bin");
- }
- const fixture = discoveryFixture(
- env,
- [
- ...installationFiles(root),
- ...(kind === "chocolatey-path" ? [win32.join(root, "bin", "git.exe")] : []),
- ],
- textFiles,
- );
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(root, "bin", "bash.exe"),
- source: kind === "scoop-config" ? "system" : "path",
- });
- },
- );
- it.each(["bin\\bash.exe", "cmd\\git.exe", "git-bash.exe"])(
- "rejects an added installation root missing %s",
- async (missingFile) => {
- const root = "D:\\IncompleteGit";
- const fixture = discoveryFixture(
- { GIT_INSTALL_ROOT: root },
- installationFiles(root).filter((path) => path !== win32.join(root, missingFile)),
- );
- expect(await discoverWindowsGitBash(fixture)).toBeUndefined();
- },
- );
- it("continues from stale environment roots to a valid later installation", async () => {
- const root = "E:\\ScoopGlobal\\apps\\git\\current";
- const fixture = discoveryFixture(
- {
- GIT_INSTALL_ROOT: "D:\\RemovedGit",
- SCOOP: "D:\\RemovedScoop",
- SCOOP_GLOBAL: "E:\\ScoopGlobal",
- },
- installationFiles(root),
- );
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(root, "bin", "bash.exe"),
- source: "system",
- });
- });
- it.each(["ENOENT", "EACCES"])(
- "continues after registry and Scoop config reads fail with %s",
- async (code) => {
- const root = "E:\\ChocoTools\\git";
- const fixture = discoveryFixture(
- { USERPROFILE: "D:\\Users\\dev", ChocolateyToolsLocation: "E:\\ChocoTools" },
- installationFiles(root),
- );
- const readError = Object.assign(new Error("Unavailable fixture source"), { code });
- fixture.readRegistryInstallRoots.mockRejectedValue(readError);
- fixture.readTextFile.mockRejectedValue(readError);
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(root, "bin", "bash.exe"),
- source: "system",
- });
- expect(fixture.readRegistryInstallRoots).toHaveBeenCalled();
- expect(fixture.readTextFile).toHaveBeenCalledWith(
- "D:\\Users\\dev\\.config\\scoop\\config.json",
- );
- },
- );
- it("continues after a malformed Scoop config to a valid Chocolatey root", async () => {
- const root = "E:\\ChocoTools\\git";
- const fixture = discoveryFixture(
- { XDG_CONFIG_HOME: "D:\\UserConfig", ChocolateyToolsLocation: "E:\\ChocoTools" },
- installationFiles(root),
- { "D:\\UserConfig\\scoop\\config.json": "{invalid-json" },
- );
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(root, "bin", "bash.exe"),
- source: "system",
- });
- });
- it("does not accept arbitrary WSL, MSYS2 or Cygwin Bash executables", async () => {
- const bashPaths = [
- "C:\\Windows\\System32\\bash.exe",
- "D:\\msys64\\usr\\bin\\bash.exe",
- "D:\\cygwin64\\bin\\bash.exe",
- ];
- const fixture = discoveryFixture(
- { PATH: bashPaths.map((path) => win32.dirname(path)).join(";"), SHELL: bashPaths[1] },
- bashPaths,
- );
- expect(await discoverWindowsGitBash(fixture)).toBeUndefined();
- });
- it("uses a PATH Git Bash launcher only as a layout clue and returns bin Bash", async () => {
- const root = "E:\\PortableGit";
- const fixture = discoveryFixture({ PATH: `"${root}"` }, installationFiles(root));
- expect(await discoverWindowsGitBash(fixture)).toEqual({
- path: win32.join(root, "bin", "bash.exe"),
- source: "path",
- });
- });
- it("does not return git-bash.exe when the corresponding bin Bash is missing", async () => {
- const root = "E:\\LauncherOnly";
- const fixture = discoveryFixture({ PATH: root, GIT_INSTALL_ROOT: root }, [
- win32.join(root, "git-bash.exe"),
- win32.join(root, "cmd", "git.exe"),
- ]);
- expect(await discoverWindowsGitBash(fixture)).toBeUndefined();
- });
- it("awaits an asynchronous executable probe", async () => {
- const fixture = discoveryFixture({}, []);
- const isExecutable = vi.fn(async (path: string) => path === fixedX86BashPath);
- expect(await discoverWindowsGitBash({ ...fixture, isExecutable })).toEqual({
- path: fixedX86BashPath,
- source: "system",
- });
- expect(isExecutable).toHaveBeenCalledWith(fixedBashPath);
- expect(isExecutable).toHaveBeenCalledWith(fixedX86BashPath);
- });
- it("maps a discovered Scoop installation to the effective selection and execution provider", async () => {
- const scoopRoot = "E:\\ScoopUser";
- const root = win32.join(scoopRoot, "apps", "git", "current");
- const bashPath = win32.join(root, "bin", "bash.exe");
- const fixture = discoveryFixture({ SCOOP: scoopRoot }, installationFiles(root));
- const options = {
- env: fixture.env,
- platform: fixture.platform,
- exists: fixture.isExecutable,
- gitBashDiscovery: {
- readRegistryInstallRoots: fixture.readRegistryInstallRoots,
- readTextFile: fixture.readTextFile,
- },
- };
- const resolution = await resolveEffectiveBashShellSelection(options);
- expect(resolution.selection).toMatchObject({
- dialect: "git-bash",
- display: { name: "Git Bash" },
- path: bashPath,
- source: "auto-detected",
- });
- expect(resolution.provider).toEqual({
- dialect: "git-bash",
- envOverlay: { GIT_EDITOR: "true", SHELL: bashPath },
- file: bashPath,
- shell: false,
- });
- expect(
- await resolveExecutionCommand(
- { mode: "shell", command: "printf ok", shellProfile: "posix-bash" },
- options,
- ),
- ).toMatchObject({
- args: ["-c", "-l", "printf ok"],
- cwdDialect: "git-bash",
- envOverlay: { GIT_EDITOR: "true", SHELL: bashPath },
- file: bashPath,
- shell: false,
- });
- });
- it.each(["user-config", "auto-detected"] as const)(
- "does not read installation sources for a valid %s shell selection",
- async (source) => {
- const bashPath = "E:\\SelectedGit\\bin\\bash.exe";
- const fixture = discoveryFixture({ SCOOP: "D:\\OtherScoop" }, [bashPath]);
- const override = {
- dialect: "git-bash" as const,
- display: { name: "Git Bash" },
- path: bashPath,
- source,
- };
- const options = {
- env: fixture.env,
- platform: fixture.platform,
- exists: fixture.isExecutable,
- gitBashDiscovery: {
- readRegistryInstallRoots: fixture.readRegistryInstallRoots,
- readTextFile: fixture.readTextFile,
- },
- };
- // 用户选择和 runtime 快照已有确定的路径;异步发现不能重新读取安装来源覆盖它。
- const resolution = await resolveEffectiveBashShellSelection({ ...options, override });
- expect(resolution.selection).toMatchObject(override);
- expect(resolution.provider).toMatchObject({ file: bashPath, shell: false });
- expect(
- await resolveExecutionCommand(
- {
- mode: "shell",
- command: "printf ok",
- shellProfile: "posix-bash",
- shellOverride: override,
- },
- options,
- ),
- ).toMatchObject({ file: bashPath, shell: false });
- expect(fixture.readRegistryInstallRoots).not.toHaveBeenCalled();
- expect(fixture.readTextFile).not.toHaveBeenCalled();
- if (source === "auto-detected") expect(fixture.isExecutable).not.toHaveBeenCalled();
- },
- );
- it.each(["linux", "darwin"])("does not probe any Windows source on %s", async (platform) => {
- const fixture = discoveryFixture(
- { PATH: "C:\\Program Files\\Git\\cmd", GIT_INSTALL_ROOT: "C:\\Program Files\\Git" },
- [fixedBashPath],
- );
- expect(await discoverWindowsGitBash({ ...fixture, platform })).toBeUndefined();
- expect(fixture.isExecutable).not.toHaveBeenCalled();
- expect(fixture.readRegistryInstallRoots).not.toHaveBeenCalled();
- expect(fixture.readTextFile).not.toHaveBeenCalled();
- });
- });
- function isProcessAlive(pid: number): boolean {
- try {
- process.kill(pid, 0);
- } catch {
- return false;
- }
- if (process.platform === "win32") {
- return true;
- }
- try {
- const state = execFileSync("ps", ["-o", "stat=", "-p", String(pid)], {
- encoding: "utf8",
- }).trim();
- return state.length > 0 && !state.startsWith("Z");
- } catch {
- return false;
- }
- }
- function quotePosixShellArgument(value: string): string {
- return `'${value.replaceAll("'", `'\\''`)}'`;
- }
- function readPosixProcessGroupId(pid: number): number {
- return Number(
- execFileSync("ps", ["-o", "pgid=", "-p", String(pid)], { encoding: "utf8" }).trim(),
- );
- }
|