remoteDeploy.test.ts 160 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565
  1. import { execFileSync } from "node:child_process";
  2. import { createHash } from "node:crypto";
  3. import { createServer } from "node:http";
  4. import { cp, mkdtemp, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
  5. import { tmpdir } from "node:os";
  6. import { basename, dirname, join } from "node:path";
  7. import { PassThrough } from "node:stream";
  8. import type { AddressInfo } from "node:net";
  9. import { afterEach, describe, expect, it, vi } from "vitest";
  10. import type { IDisposable, Event } from "@zcode/rpc";
  11. import {
  12. getRemoteRuntimeToolsForPlatform,
  13. ZCODE_AGENT_RUNTIME,
  14. ZCODE_RUNTIME_ENV_KEY,
  15. ZCODE_VERSION,
  16. } from "@zcode/shared";
  17. import type { IRemoteBackend, StdioStream } from "@zcode/server/remote/backend.js";
  18. import { deployZCodeAgentRuntime } from "@zcode/server/remote/zcodeAgentDeploy.js";
  19. import { deployServer } from "@zcode/server/remote/deploy.js";
  20. import {
  21. createRemoteComponentVersionResolver,
  22. deployNodeRuntime,
  23. } from "@zcode/server/remote/remoteAssetDeployDecision.js";
  24. import { buildRemoteExecutableReplaceCommand } from "@zcode/server/remote/deployShared.js";
  25. import { ensureRemoteReleaseDirFromCdn } from "@zcode/server/remote/remoteAssetCache.js";
  26. import {
  27. fetchRemoteDownloadManifest,
  28. type RemoteAssetInstaller,
  29. } from "@zcode/server/remote/remoteAssetInstaller.js";
  30. import { createTarGzArchive } from "@zcode/server/remote/localTarGz.js";
  31. import { buildRemoteAgentBundleWrapper } from "@zcode/server/remote/zcodeAgentBundleWrapper.js";
  32. import {
  33. REMOTE_AGENT_OFFICIAL_PLUGIN_INCLUDED_TOP_LEVEL_PATHS,
  34. REMOTE_AGENT_OFFICIAL_PLUGIN_PACKAGE_NAMES,
  35. REMOTE_AGENT_OFFICIAL_PLUGIN_REQUIRED_RELATIVE_PATHS,
  36. } from "@zcode/server/remote/zcodeAgentOfficialPluginAssets.js";
  37. const retiredProtocolPrefix = `${"a"}${"cp"}`;
  38. const retiredProxyRuntimeId = `${retiredProtocolPrefix}-proxy-runtime`;
  39. // 远端 ZCode Agent bundle 文件名(与 REMOTE_AGENT_BUNDLE_NAME 保持一致)。
  40. const REMOTE_AGENT_BUNDLE_FILE_NAME = "zcode.cjs";
  41. const REMOTE_AGENT_WRAPPER_FILE_NAME = "zcode-agent";
  42. const BROWSER_USE_REQUIRED_RELATIVE_PATHS = [
  43. // node_repl 宿主已抽成 @zcode/node-repl-host,browser-use 不再产出 dist/mcp/server.js。
  44. "browser-use-plugin/docs/api.json",
  45. "browser-use-plugin/docs/documents.json",
  46. "browser-use-plugin/docs/overview.md",
  47. "browser-use-plugin/docs/recording.md",
  48. "browser-use-plugin/docs/workflow.md",
  49. "browser-use-plugin/scripts/browser-client.mjs",
  50. "browser-use-plugin/skills/control-browser/SKILL.md",
  51. "browser-use-plugin/skills/web-gui-tester/SKILL.md",
  52. ] as const;
  53. // Bug 根因:remote fixture 曾复制一份旧的官方插件资产清单;生产合同加入 CUA SDK/docs/skill
  54. // 后 fixture 仍生成不含这些文件的 GLM archive,所有部署测试都会误报 packages 缺失。
  55. // 测试数据必须直接复用生产常量,后续新增官方资产时不能再静默漂移。
  56. const OFFICIAL_PLUGIN_PACKAGE_NAMES = REMOTE_AGENT_OFFICIAL_PLUGIN_PACKAGE_NAMES;
  57. const OFFICIAL_PLUGIN_REQUIRED_RELATIVE_PATHS =
  58. REMOTE_AGENT_OFFICIAL_PLUGIN_REQUIRED_RELATIVE_PATHS;
  59. const OFFICIAL_PLUGIN_INCLUDED_TOP_LEVEL_PATHS =
  60. REMOTE_AGENT_OFFICIAL_PLUGIN_INCLUDED_TOP_LEVEL_PATHS;
  61. const TEST_GLM_ARTIFACT_SHA256 = "a".repeat(64);
  62. type LegacyRemoteTestAgentRuntime = {
  63. binaryKind: "node-script" | "native-binary";
  64. bundledResourceDir: string;
  65. version: string;
  66. resolveEntrySegments(platform: string): string[];
  67. };
  68. function resolveTestPlatformBinaryName(binaryName: string, platform: string): string {
  69. return platform === "win32" ? `${binaryName}.exe` : binaryName;
  70. }
  71. const LEGACY_REMOTE_TEST_AGENT_RUNTIME: Record<
  72. "claude" | "opencode" | "gemini" | "codex" | "glm",
  73. LegacyRemoteTestAgentRuntime
  74. > = {
  75. claude: {
  76. binaryKind: "node-script",
  77. bundledResourceDir: retiredProtocolPrefix,
  78. version: "0.29.2",
  79. resolveEntrySegments: () => ["dist", "index.js"],
  80. },
  81. opencode: {
  82. binaryKind: "native-binary",
  83. bundledResourceDir: "opencode",
  84. version: "1.15.6",
  85. resolveEntrySegments: (platform) => [resolveTestPlatformBinaryName("opencode", platform)],
  86. },
  87. gemini: {
  88. binaryKind: "node-script",
  89. bundledResourceDir: "gemini",
  90. version: "0.37.0",
  91. resolveEntrySegments: () => ["gemini.js"],
  92. },
  93. codex: {
  94. binaryKind: "node-script",
  95. bundledResourceDir: "codex",
  96. version: "0.12.0",
  97. resolveEntrySegments: () => [
  98. "node_modules",
  99. "@zed-industries",
  100. `codex-${retiredProtocolPrefix}`,
  101. "bin",
  102. `codex-${retiredProtocolPrefix}.js`,
  103. ],
  104. },
  105. glm: {
  106. binaryKind: "native-binary",
  107. bundledResourceDir: "glm",
  108. version: ZCODE_AGENT_RUNTIME.version,
  109. resolveEntrySegments: (platform) => [resolveTestPlatformBinaryName("zcode-agent", platform)],
  110. },
  111. };
  112. type RemotePlatformKey = "linux-arm64" | "linux-x64" | "darwin-arm64" | "darwin-x64";
  113. interface RemoteComponentManifestItem {
  114. id: string;
  115. version: string;
  116. sha256: string;
  117. artifactPath: string;
  118. mount: string;
  119. }
  120. interface RemoteComponentManifest {
  121. schemaVersion: number;
  122. appVersion: string;
  123. platformArch: RemotePlatformKey;
  124. components: RemoteComponentManifestItem[];
  125. }
  126. interface RemoteComponentArtifactSpec {
  127. id: string;
  128. version: string;
  129. artifactPath: string;
  130. mount: string;
  131. sourcePath: string;
  132. }
  133. interface StageRemoteComponentArtifactsOptions {
  134. platformKey?: RemotePlatformKey;
  135. writeManifest?: boolean;
  136. mutateManifest?: (manifest: RemoteComponentManifest) => RemoteComponentManifest;
  137. }
  138. class FakeRemoteBackend implements IRemoteBackend {
  139. readonly uploads: Array<{ localPath: string; remotePath: string }> = [];
  140. readonly commands: string[] = [];
  141. readonly remoteFiles = new Map<string, string>();
  142. readonly lockReleaseMarkers: string[] = [];
  143. private readonly commandPlans: Array<{
  144. matcher: RegExp;
  145. exitCode: number;
  146. stdoutText?: string;
  147. stderrText?: string;
  148. onExec?: () => void;
  149. }>;
  150. private readonly serverVersions: Array<string | (() => string)>;
  151. private readonly lockCloseCode: number;
  152. private readonly lockAcquireGate?: Promise<void>;
  153. constructor(
  154. initialFiles: Record<string, string> = {},
  155. options: {
  156. commandPlans?: Array<{
  157. matcher: RegExp;
  158. exitCode: number;
  159. stdoutText?: string;
  160. stderrText?: string;
  161. onExec?: () => void;
  162. }>;
  163. serverVersion?: string | (() => string);
  164. serverVersions?: Array<string | (() => string)>;
  165. lockCloseCode?: number;
  166. lockAcquireGate?: Promise<void>;
  167. } = {},
  168. ) {
  169. this.commandPlans = options.commandPlans ?? [];
  170. this.serverVersions = options.serverVersions?.slice() ?? [
  171. options.serverVersion ?? ZCODE_VERSION,
  172. ];
  173. this.lockCloseCode = options.lockCloseCode ?? 0;
  174. this.lockAcquireGate = options.lockAcquireGate;
  175. for (const [path, content] of Object.entries(initialFiles)) {
  176. this.remoteFiles.set(path, content);
  177. }
  178. }
  179. dispose(): void {}
  180. async detect() {
  181. return { platform: "linux", arch: "arm64" };
  182. }
  183. async upload(localPath: string, remotePath: string): Promise<void> {
  184. this.uploads.push({ localPath, remotePath });
  185. this.remoteFiles.set(remotePath, await readFile(localPath, "utf8"));
  186. }
  187. async exec(command: string): Promise<StdioStream> {
  188. this.commands.push(command);
  189. const lockOwner = command.match(/\.holder-([\w-]+)\.sh/u)?.[1];
  190. if (lockOwner) {
  191. return createLockHolderStream(
  192. `zcode-deploy-lock-acquired:${lockOwner}`,
  193. this.lockReleaseMarkers,
  194. this.lockCloseCode,
  195. this.lockAcquireGate,
  196. );
  197. }
  198. const versionCommand = `"${"$HOME"}"'/.zcode/server/node' "${"$HOME"}"'/.zcode/server/zcode-server.cjs' --version`;
  199. if (command === versionCommand) {
  200. const versionSource =
  201. this.serverVersions.length > 1
  202. ? this.serverVersions.shift()!
  203. : (this.serverVersions[0] ?? ZCODE_VERSION);
  204. const version = typeof versionSource === "function" ? versionSource() : versionSource;
  205. return createClosedStream(`${version}\n`);
  206. }
  207. const matchedPlan = this.commandPlans.find((plan) => plan.matcher.test(command));
  208. if (matchedPlan) {
  209. matchedPlan.onExec?.();
  210. return createClosedStream(matchedPlan.stdoutText ?? "", {
  211. exitCode: matchedPlan.exitCode,
  212. stderrText: matchedPlan.stderrText,
  213. });
  214. }
  215. return createClosedStream();
  216. }
  217. async exists(remotePath: string): Promise<boolean> {
  218. return (
  219. this.remoteFiles.has(remotePath) ||
  220. remotePath === "~/.zcode/server/node" ||
  221. remotePath === "~/.zcode/server/zcode-server.cjs"
  222. );
  223. }
  224. async readFile(remotePath: string): Promise<string> {
  225. const content = this.remoteFiles.get(remotePath);
  226. if (content == null) {
  227. throw new Error(`ENOENT: ${remotePath}`);
  228. }
  229. return content;
  230. }
  231. }
  232. function createLockHolderStream(
  233. acquiredMarker: string,
  234. releaseMarkers: string[],
  235. closeCode = 0,
  236. acquireGate?: Promise<void>,
  237. ): StdioStream {
  238. const stdin = new PassThrough();
  239. const stdout = new PassThrough();
  240. const stderr = new PassThrough();
  241. const closeListeners: Array<(code: number) => void> = [];
  242. let closed = false;
  243. const close = () => {
  244. if (closed) return;
  245. closed = true;
  246. stdout.end();
  247. stderr.end();
  248. for (const listener of closeListeners) listener(closeCode);
  249. };
  250. stdin.on("data", (chunk: Buffer) => releaseMarkers.push(chunk.toString().trim()));
  251. stdin.on("end", close);
  252. queueMicrotask(() => {
  253. void (acquireGate ?? Promise.resolve()).then(() => {
  254. stdout.write(`${acquiredMarker}\n`);
  255. });
  256. });
  257. return {
  258. stdin,
  259. stdout,
  260. stderr,
  261. onClose(listener) {
  262. closeListeners.push(listener);
  263. return { dispose() {} };
  264. },
  265. };
  266. }
  267. function hasUploadForStagingTarget(backend: FakeRemoteBackend, stagingTarget: string): boolean {
  268. return findUploadForStagingTarget(backend, stagingTarget) !== undefined;
  269. }
  270. function findUploadForStagingTarget(
  271. backend: FakeRemoteBackend,
  272. stagingTarget: string,
  273. ): { localPath: string; remotePath: string } | undefined {
  274. return backend.uploads.find(
  275. (upload) =>
  276. upload.remotePath === stagingTarget || upload.remotePath.startsWith(`${stagingTarget}-`),
  277. );
  278. }
  279. class FailFirstGlmUploadRemoteBackend extends FakeRemoteBackend {
  280. private shouldFailGlmUpload = true;
  281. override async upload(localPath: string, remotePath: string): Promise<void> {
  282. if (
  283. this.shouldFailGlmUpload &&
  284. (remotePath === "~/.zcode/server/agents/glm/zcode.cjs.new" ||
  285. remotePath.startsWith("~/.zcode/server/agents/glm/zcode.cjs.new-"))
  286. ) {
  287. this.shouldFailGlmUpload = false;
  288. throw new Error("mock glm upload failed");
  289. }
  290. await super.upload(localPath, remotePath);
  291. }
  292. }
  293. class FailFirstNodePtyInstallRemoteBackend extends FakeRemoteBackend {
  294. private shouldFailNodePtyInstall = true;
  295. override async exec(command: string): Promise<StdioStream> {
  296. if (
  297. this.shouldFailNodePtyInstall &&
  298. command.includes("/node-pty/") &&
  299. command.includes("pty.node")
  300. ) {
  301. this.shouldFailNodePtyInstall = false;
  302. this.commands.push(command);
  303. return createClosedStream("", {
  304. exitCode: 1,
  305. stderrText: "mock node-pty install failed",
  306. });
  307. }
  308. return super.exec(command);
  309. }
  310. }
  311. class FakeWslRemoteBackend extends FakeRemoteBackend {
  312. readonly kind = "wsl" as const;
  313. }
  314. class FakeFileOnlyExistsRemoteBackend extends FakeRemoteBackend {
  315. constructor(
  316. initialFiles: Record<string, string>,
  317. private readonly directoryPaths: readonly string[],
  318. ) {
  319. super(initialFiles);
  320. }
  321. override async exists(remotePath: string): Promise<boolean> {
  322. if (this.directoryPaths.includes(remotePath)) {
  323. return false;
  324. }
  325. return super.exists(remotePath);
  326. }
  327. }
  328. function createClosedStream(
  329. stdoutText = "",
  330. options: {
  331. exitCode?: number;
  332. stderrText?: string;
  333. } = {},
  334. ): StdioStream {
  335. const stdin = new PassThrough();
  336. const stdout = new PassThrough();
  337. const stderr = new PassThrough();
  338. const onClose: Event<number> = (listener: (code: number) => void): IDisposable => {
  339. queueMicrotask(() => {
  340. if (stdoutText.length > 0) {
  341. stdout.write(stdoutText);
  342. }
  343. stdout.end();
  344. if (options.stderrText) {
  345. stderr.write(options.stderrText);
  346. }
  347. stderr.end();
  348. listener(options.exitCode ?? 0);
  349. });
  350. return { dispose() {} };
  351. };
  352. return { stdin, stdout, stderr, onClose };
  353. }
  354. async function stageRemoteRuntimeRelease(
  355. rootDir: string,
  356. options: {
  357. platform: "linux" | "darwin";
  358. arch: "arm64" | "x64";
  359. } = {
  360. platform: "linux",
  361. arch: "arm64",
  362. },
  363. ): Promise<void> {
  364. const platformKey = `${options.platform}-${options.arch}`;
  365. const releaseDir = join(rootDir, "releases", ZCODE_VERSION);
  366. const nodeDir = join(releaseDir, "node", platformKey);
  367. const serverDir = join(releaseDir, "server");
  368. const nodePtyDir = join(releaseDir, "node-pty", platformKey);
  369. await mkdir(nodeDir, { recursive: true });
  370. await mkdir(serverDir, { recursive: true });
  371. await mkdir(nodePtyDir, { recursive: true });
  372. await writeFile(join(nodeDir, "node"), "node runtime", "utf8");
  373. await writeFile(join(serverDir, "zcode-server.cjs"), "// remote server bundle\n", "utf8");
  374. await writeFile(join(nodePtyDir, "pty.node"), "node-pty prebuild", "utf8");
  375. if (options.platform === "darwin") {
  376. await writeFile(join(nodePtyDir, "spawn-helper"), "node-pty spawn helper", "utf8");
  377. }
  378. for (const [provider, runtime] of Object.entries(LEGACY_REMOTE_TEST_AGENT_RUNTIME)) {
  379. if (runtime.binaryKind === "node-script") {
  380. const providerDir = join(
  381. releaseDir,
  382. retiredProtocolPrefix,
  383. platformKey,
  384. runtime.bundledResourceDir,
  385. );
  386. const entryPath = join(providerDir, ...runtime.resolveEntrySegments(options.platform));
  387. await mkdir(dirname(entryPath), { recursive: true });
  388. await writeFile(entryPath, `// ${provider} test entry\n`, "utf8");
  389. if (provider === "claude") {
  390. const claudeNativePath = join(
  391. providerDir,
  392. "node_modules",
  393. "@anthropic-ai",
  394. `claude-agent-sdk-${platformKey}`,
  395. "claude",
  396. );
  397. await mkdir(dirname(claudeNativePath), { recursive: true });
  398. await writeFile(claudeNativePath, "claude native binary", "utf8");
  399. }
  400. await writeFile(
  401. join(providerDir, ".bundle-meta.json"),
  402. JSON.stringify(
  403. {
  404. provider,
  405. version: runtime.version,
  406. platform: platformKey,
  407. },
  408. null,
  409. 2,
  410. ),
  411. "utf8",
  412. );
  413. continue;
  414. }
  415. const entrySegments = runtime.resolveEntrySegments(options.platform);
  416. const binaryName = entrySegments[entrySegments.length - 1];
  417. if (!binaryName) {
  418. throw new Error(`Missing binary name for provider: ${provider}`);
  419. }
  420. const binaryDir = join(releaseDir, runtime.bundledResourceDir, platformKey);
  421. await mkdir(binaryDir, { recursive: true });
  422. await writeFile(join(binaryDir, binaryName), `${provider} binary`, "utf8");
  423. // ZCode Agent(glm)远端不再发原生二进制,而是发编译产物 zcode.cjs,
  424. // 由远端已部署的 node 通过 wrapper 执行,故 source release 需提供该 bundle。
  425. if (provider === "glm") {
  426. await writeFile(join(binaryDir, REMOTE_AGENT_BUNDLE_FILE_NAME), `${provider} bundle`, "utf8");
  427. for (const relativePath of OFFICIAL_PLUGIN_REQUIRED_RELATIVE_PATHS) {
  428. await mkdir(dirname(join(binaryDir, "packages", relativePath)), {
  429. recursive: true,
  430. });
  431. await writeFile(
  432. join(binaryDir, "packages", relativePath),
  433. `${provider} official plugin ${relativePath}`,
  434. "utf8",
  435. );
  436. }
  437. }
  438. }
  439. for (const { runtime } of getRemoteRuntimeToolsForPlatform(options.platform)) {
  440. const entrySegments = runtime.resolveEntrySegments(options.platform);
  441. const binaryName = entrySegments[entrySegments.length - 1];
  442. if (!binaryName) {
  443. throw new Error(`Missing binary name for runtime tool: ${runtime.bundledResourceDir}`);
  444. }
  445. const binaryDir = join(releaseDir, "tools", platformKey, runtime.bundledResourceDir);
  446. await mkdir(binaryDir, { recursive: true });
  447. await writeFile(join(binaryDir, binaryName), `${runtime.bundledResourceDir} binary`, "utf8");
  448. }
  449. }
  450. function createFullyDeployedRemoteFiles(platformKey: RemotePlatformKey): Record<string, string> {
  451. const [platform] = platformKey.split("-") as ["linux" | "darwin", string];
  452. const files: Record<string, string> = {
  453. "~/.zcode/server/build/Release/pty.node": "deployed node-pty",
  454. };
  455. if (platform === "darwin") {
  456. files["~/.zcode/server/build/Release/spawn-helper"] = "deployed spawn helper";
  457. }
  458. for (const [provider, runtime] of Object.entries(LEGACY_REMOTE_TEST_AGENT_RUNTIME)) {
  459. const remoteProviderDir = `~/.zcode/server/agents/${runtime.bundledResourceDir}`;
  460. files[`${remoteProviderDir}/.version`] = `${runtime.version}\n`;
  461. if (runtime.binaryKind === "node-script") {
  462. files[`${remoteProviderDir}/.bundle-meta.json`] = JSON.stringify({
  463. provider,
  464. version: runtime.version,
  465. platform: platformKey,
  466. });
  467. const entryPath = runtime.resolveEntrySegments(platform).join("/");
  468. files[`${remoteProviderDir}/${entryPath}`] = `${provider} entry`;
  469. if (provider === "claude") {
  470. files[
  471. `${remoteProviderDir}/node_modules/@anthropic-ai/claude-agent-sdk-${platformKey}/claude`
  472. ] = "claude native binary";
  473. }
  474. } else if (provider === "glm") {
  475. // ZCode Agent 远端部署后:wrapper(zcode-agent)+ 编译产物 bundle(zcode.cjs)。
  476. const entrySegments = runtime.resolveEntrySegments(platform);
  477. const wrapperName = entrySegments[entrySegments.length - 1];
  478. if (wrapperName) {
  479. files[`${remoteProviderDir}/${wrapperName}`] = `${provider} wrapper`;
  480. }
  481. files[`${remoteProviderDir}/${REMOTE_AGENT_BUNDLE_FILE_NAME}`] = `${provider} bundle`;
  482. for (const relativePath of OFFICIAL_PLUGIN_REQUIRED_RELATIVE_PATHS) {
  483. files[`${remoteProviderDir}/packages/${relativePath}`] =
  484. `${provider} official plugin ${relativePath}`;
  485. }
  486. } else {
  487. const entrySegments = runtime.resolveEntrySegments(platform);
  488. const binaryName = entrySegments[entrySegments.length - 1];
  489. if (binaryName) {
  490. files[`${remoteProviderDir}/${binaryName}`] = `${provider} binary`;
  491. }
  492. }
  493. }
  494. for (const { runtime, version } of getRemoteRuntimeToolsForPlatform(platform)) {
  495. files[`~/.zcode/server/tools/${runtime.bundledResourceDir}/.version`] = `${version}\n`;
  496. const entrySegments = runtime.resolveEntrySegments(platform);
  497. const binaryName = entrySegments[entrySegments.length - 1];
  498. if (binaryName) {
  499. files[`~/.zcode/server/tools/${runtime.bundledResourceDir}/${binaryName}`] =
  500. `${runtime.bundledResourceDir} binary`;
  501. }
  502. }
  503. return files;
  504. }
  505. function addMatchingGlmAndServerArtifactIdentities(
  506. remoteFiles: Record<string, string>,
  507. manifest: RemoteComponentManifest,
  508. platformKey: RemotePlatformKey,
  509. version = LEGACY_REMOTE_TEST_AGENT_RUNTIME.glm.version,
  510. ): void {
  511. addMatchingGlmArtifactIdentity(remoteFiles, manifest, platformKey, version);
  512. addMatchingServerBundleArtifactIdentity(remoteFiles, manifest, platformKey);
  513. }
  514. function addMatchingGlmArtifactIdentity(
  515. remoteFiles: Record<string, string>,
  516. manifest: RemoteComponentManifest,
  517. platformKey: RemotePlatformKey,
  518. version = LEGACY_REMOTE_TEST_AGENT_RUNTIME.glm.version,
  519. ): void {
  520. const glm = manifest.components.find((component) => component.id === "glm");
  521. if (!glm) {
  522. throw new Error("missing glm component in staged manifest");
  523. }
  524. remoteFiles["~/.zcode/server/.asset-components/glm.json"] = JSON.stringify({
  525. id: "glm",
  526. version,
  527. sha256: glm.sha256,
  528. platformArch: platformKey,
  529. });
  530. }
  531. function addMatchingServerBundleArtifactIdentity(
  532. remoteFiles: Record<string, string>,
  533. manifest: RemoteComponentManifest,
  534. platformKey: RemotePlatformKey,
  535. ): void {
  536. const serverBundle = findManifestComponent(manifest, "server-bundle");
  537. remoteFiles["~/.zcode/server/.asset-components/server-bundle.json"] = JSON.stringify({
  538. id: "server-bundle",
  539. version: serverBundle.version,
  540. sha256: serverBundle.sha256,
  541. platformArch: platformKey,
  542. });
  543. }
  544. function findManifestComponent(
  545. manifest: RemoteComponentManifest,
  546. componentId: string,
  547. ): RemoteComponentManifestItem {
  548. const component = manifest.components.find((item) => item.id === componentId);
  549. if (!component) {
  550. throw new Error(`missing component in staged manifest: ${componentId}`);
  551. }
  552. return component;
  553. }
  554. function createRemoteAssetComponentMeta(
  555. id: string,
  556. version: string,
  557. platformArch: RemotePlatformKey,
  558. ): string {
  559. return JSON.stringify({
  560. id,
  561. version,
  562. platformArch,
  563. });
  564. }
  565. async function writeTestOfficialPluginPackages(repoDir: string): Promise<void> {
  566. await Promise.all(
  567. OFFICIAL_PLUGIN_PACKAGE_NAMES.map(async (pluginName) => {
  568. const manifestPath = join(
  569. repoDir,
  570. "apps",
  571. "zcode-cli",
  572. "packages",
  573. pluginName,
  574. ".zcode-plugin",
  575. "plugin.json",
  576. );
  577. await mkdir(dirname(manifestPath), { recursive: true });
  578. const pluginManifestName =
  579. pluginName === "zcode-cua-plugin" ? "computer-use" : pluginName.replace(/-plugin$/u, "");
  580. await writeFile(
  581. manifestPath,
  582. JSON.stringify({
  583. name: pluginManifestName,
  584. version: "0.1.0",
  585. }),
  586. "utf8",
  587. );
  588. const pluginRoot = dirname(dirname(manifestPath));
  589. const requiredAssetPaths = OFFICIAL_PLUGIN_REQUIRED_RELATIVE_PATHS.filter((relativePath) =>
  590. relativePath.startsWith(`${pluginName}/`),
  591. )
  592. .map((relativePath) => relativePath.slice(pluginName.length + 1))
  593. .filter((relativePath) => relativePath !== ".zcode-plugin/plugin.json");
  594. await Promise.all(
  595. requiredAssetPaths.map(async (relativePath) => {
  596. const assetPath = join(pluginRoot, ...relativePath.split("/"));
  597. await mkdir(dirname(assetPath), { recursive: true });
  598. await writeFile(assetPath, `${pluginName} asset ${relativePath}\n`, "utf8");
  599. }),
  600. );
  601. }),
  602. );
  603. }
  604. async function stageRemoteAssetArchive(
  605. mockCdnDir: string,
  606. outputRoot: string,
  607. options?: {
  608. platformKey?: "linux-arm64" | "linux-x64" | "darwin-arm64" | "darwin-x64";
  609. useLegacyFileName?: boolean;
  610. },
  611. ): Promise<void> {
  612. const sourceReleaseDir = join(mockCdnDir, "releases", ZCODE_VERSION);
  613. const outputVersionDir = join(outputRoot, ZCODE_VERSION);
  614. const platformKey = options?.platformKey ?? "linux-arm64";
  615. const archiveFileName = options?.useLegacyFileName
  616. ? "remote-assets.tar.gz"
  617. : `remote-assets-${platformKey}.tar.gz`;
  618. const checksumFileName = options?.useLegacyFileName
  619. ? "remote-assets.sha256"
  620. : `remote-assets-${platformKey}.sha256`;
  621. const archivePath = join(outputVersionDir, archiveFileName);
  622. const checksumPath = join(outputVersionDir, checksumFileName);
  623. await mkdir(outputVersionDir, { recursive: true });
  624. await createTarGzArchive(archivePath, [
  625. { sourcePath: join(sourceReleaseDir, "server"), archivePath: "server" },
  626. {
  627. sourcePath: join(sourceReleaseDir, "node", platformKey),
  628. archivePath: `node/${platformKey}`,
  629. },
  630. {
  631. sourcePath: join(sourceReleaseDir, "node-pty", platformKey),
  632. archivePath: `node-pty/${platformKey}`,
  633. },
  634. {
  635. sourcePath: join(sourceReleaseDir, retiredProtocolPrefix, platformKey),
  636. archivePath: `${retiredProtocolPrefix}/${platformKey}`,
  637. },
  638. {
  639. sourcePath: join(sourceReleaseDir, "opencode", platformKey),
  640. archivePath: `opencode/${platformKey}`,
  641. },
  642. {
  643. sourcePath: join(sourceReleaseDir, "glm", platformKey),
  644. archivePath: `glm/${platformKey}`,
  645. },
  646. {
  647. sourcePath: join(sourceReleaseDir, "tools", platformKey),
  648. archivePath: `tools/${platformKey}`,
  649. },
  650. ]);
  651. const checksum = await computeSha256(archivePath);
  652. await writeFile(checksumPath, `${checksum}\n`, "utf8");
  653. }
  654. function buildRemoteComponentArtifactSpecs(
  655. platformKey: RemotePlatformKey,
  656. ): RemoteComponentArtifactSpec[] {
  657. const specs: RemoteComponentArtifactSpec[] = [
  658. {
  659. id: "server-bundle",
  660. version: `${ZCODE_VERSION}-server-bundle`,
  661. artifactPath: `components/${platformKey}/server-bundle/${ZCODE_VERSION}-server-bundle.tar.gz`,
  662. mount: "server",
  663. sourcePath: "server",
  664. },
  665. {
  666. id: "node-runtime",
  667. version: "24.10.0-node-runtime",
  668. artifactPath: `components/${platformKey}/node-runtime/24.10.0-node-runtime.tar.gz`,
  669. mount: `node/${platformKey}`,
  670. sourcePath: `node/${platformKey}`,
  671. },
  672. {
  673. id: "node-pty",
  674. version: "1.0.0-node-pty",
  675. artifactPath: `components/${platformKey}/node-pty/1.0.0-node-pty.tar.gz`,
  676. mount: `node-pty/${platformKey}`,
  677. sourcePath: `node-pty/${platformKey}`,
  678. },
  679. ];
  680. for (const [provider, runtime] of Object.entries(LEGACY_REMOTE_TEST_AGENT_RUNTIME)) {
  681. if (runtime.binaryKind === "node-script") {
  682. specs.push({
  683. id: `${retiredProtocolPrefix}-${provider}`,
  684. version: `${runtime.version}-${provider}`,
  685. artifactPath: `components/${platformKey}/${retiredProtocolPrefix}-${provider}/${runtime.version}-${provider}.tar.gz`,
  686. mount: `${retiredProtocolPrefix}/${platformKey}/${runtime.bundledResourceDir}`,
  687. sourcePath: `${retiredProtocolPrefix}/${platformKey}/${runtime.bundledResourceDir}`,
  688. });
  689. continue;
  690. }
  691. specs.push({
  692. id: provider,
  693. version: `${runtime.version}-${provider}`,
  694. artifactPath: `components/${platformKey}/${provider}/${runtime.version}-${provider}.tar.gz`,
  695. mount: `${runtime.bundledResourceDir}/${platformKey}`,
  696. sourcePath: `${runtime.bundledResourceDir}/${platformKey}`,
  697. });
  698. }
  699. const [platform] = platformKey.split("-");
  700. for (const { runtime, version } of getRemoteRuntimeToolsForPlatform(platform)) {
  701. specs.push({
  702. id: runtime.bundledResourceDir,
  703. version: `${version}-${runtime.bundledResourceDir}`,
  704. artifactPath: `components/${platformKey}/${runtime.bundledResourceDir}/${version}-${runtime.bundledResourceDir}.tar.gz`,
  705. mount: `tools/${platformKey}/${runtime.bundledResourceDir}`,
  706. sourcePath: `tools/${platformKey}/${runtime.bundledResourceDir}`,
  707. });
  708. }
  709. // 同一 id 在 manifest 中必须唯一,避免后续组装时覆盖导致断言失真。
  710. const duplicatedIds = specs
  711. .map((spec) => spec.id)
  712. .filter((id, index, ids) => ids.indexOf(id) !== index);
  713. if (duplicatedIds.length > 0) {
  714. throw new Error(`Duplicated component ids in staged manifest: ${duplicatedIds.join(", ")}`);
  715. }
  716. return specs;
  717. }
  718. async function copySourcePathContentToDir(sourcePath: string, targetDir: string): Promise<void> {
  719. const sourceStat = await stat(sourcePath);
  720. if (sourceStat.isDirectory()) {
  721. const children = await readdir(sourcePath);
  722. await Promise.all(
  723. children.map((child) =>
  724. cp(join(sourcePath, child), join(targetDir, child), {
  725. recursive: true,
  726. }),
  727. ),
  728. );
  729. return;
  730. }
  731. await cp(sourcePath, join(targetDir, basename(sourcePath)));
  732. }
  733. async function stageComponentArchive(
  734. sourceReleaseDir: string,
  735. outputRoot: string,
  736. spec: RemoteComponentArtifactSpec,
  737. ): Promise<string> {
  738. const stagingBase = join(outputRoot, ".component-staging");
  739. await mkdir(stagingBase, { recursive: true });
  740. const stagingDir = await mkdtemp(join(stagingBase, `${spec.id}-`));
  741. const archivePath = join(outputRoot, spec.artifactPath);
  742. try {
  743. await copySourcePathContentToDir(join(sourceReleaseDir, spec.sourcePath), stagingDir);
  744. await mkdir(dirname(archivePath), { recursive: true });
  745. const stagedEntries = await readdir(stagingDir);
  746. await createTarGzArchive(
  747. archivePath,
  748. stagedEntries.map((entry) => ({
  749. sourcePath: join(stagingDir, entry),
  750. archivePath: entry,
  751. })),
  752. );
  753. return await computeSha256(archivePath);
  754. } finally {
  755. await rm(stagingDir, { recursive: true, force: true });
  756. }
  757. }
  758. async function stageRemoteComponentArtifacts(
  759. mockCdnDir: string,
  760. outputRoot: string,
  761. options?: StageRemoteComponentArtifactsOptions,
  762. ): Promise<RemoteComponentManifest> {
  763. const platformKey = options?.platformKey ?? "linux-arm64";
  764. const sourceReleaseDir = join(mockCdnDir, "releases", ZCODE_VERSION);
  765. const outputVersionDir = join(outputRoot, ZCODE_VERSION);
  766. const componentSpecs = buildRemoteComponentArtifactSpecs(platformKey);
  767. const components: RemoteComponentManifestItem[] = [];
  768. await mkdir(outputVersionDir, { recursive: true });
  769. for (const spec of componentSpecs) {
  770. const sha256 = await stageComponentArchive(sourceReleaseDir, outputRoot, spec);
  771. components.push({
  772. id: spec.id,
  773. version: spec.version,
  774. sha256,
  775. artifactPath: spec.artifactPath,
  776. mount: spec.mount,
  777. });
  778. }
  779. const manifest = options?.mutateManifest
  780. ? options.mutateManifest({
  781. schemaVersion: 1,
  782. appVersion: ZCODE_VERSION,
  783. platformArch: platformKey,
  784. components,
  785. })
  786. : {
  787. schemaVersion: 1,
  788. appVersion: ZCODE_VERSION,
  789. platformArch: platformKey,
  790. components,
  791. };
  792. if (options?.writeManifest !== false) {
  793. const manifestPath = join(outputVersionDir, `manifest-${platformKey}.json`);
  794. await writeFile(manifestPath, JSON.stringify(manifest, null, 2), "utf8");
  795. }
  796. return manifest;
  797. }
  798. async function computeSha256(filePath: string): Promise<string> {
  799. const content = await readFile(filePath);
  800. return createHash("sha256").update(content).digest("hex");
  801. }
  802. async function computeDevelopmentAgentAssetsSha256ForTest(
  803. repoDir: string,
  804. cliBundlePath: string,
  805. ): Promise<string> {
  806. const hash = createHash("sha256");
  807. hash.update("bundle:zcode.cjs\n");
  808. hash.update(await readFile(cliBundlePath));
  809. for (const packageName of OFFICIAL_PLUGIN_PACKAGE_NAMES) {
  810. const packageRoot = join(repoDir, "apps", "zcode-cli", "packages", packageName);
  811. hash.update(`plugin:${packageName}\n`);
  812. for (const topLevelPath of OFFICIAL_PLUGIN_INCLUDED_TOP_LEVEL_PATHS) {
  813. const sourcePath = join(packageRoot, topLevelPath);
  814. try {
  815. await hashLocalPathForTest(hash, sourcePath, `${packageName}/${topLevelPath}`);
  816. } catch {
  817. // 测试 fixture 只写最小 manifest,缺失的可选目录与生产逻辑一致忽略。
  818. }
  819. }
  820. }
  821. return hash.digest("hex");
  822. }
  823. async function hashLocalPathForTest(
  824. hash: ReturnType<typeof createHash>,
  825. filePath: string,
  826. relativePath: string,
  827. ): Promise<void> {
  828. const fileStat = await stat(filePath);
  829. if (fileStat.isDirectory()) {
  830. hash.update(`dir:${relativePath}\n`);
  831. const children = (await readdir(filePath)).sort((left, right) =>
  832. left.localeCompare(right, "en"),
  833. );
  834. for (const child of children) {
  835. await hashLocalPathForTest(hash, join(filePath, child), `${relativePath}/${child}`);
  836. }
  837. return;
  838. }
  839. if (!fileStat.isFile()) {
  840. return;
  841. }
  842. hash.update(`file:${relativePath}:${fileStat.mode & 0o777}:${fileStat.size}\n`);
  843. hash.update(await readFile(filePath));
  844. }
  845. async function hashFileContent(
  846. hash: ReturnType<typeof createHash>,
  847. filePath: string,
  848. relativePath: string,
  849. ): Promise<void> {
  850. const fileStat = await stat(filePath);
  851. hash.update(`file:${relativePath}:${fileStat.mode & 0o777}:${fileStat.size}\n`);
  852. hash.update(await readFile(filePath));
  853. }
  854. async function hashDirectoryContent(
  855. hash: ReturnType<typeof createHash>,
  856. rootDir: string,
  857. relativeDir = "",
  858. ): Promise<void> {
  859. const entries = (await readdir(rootDir, { withFileTypes: true })).sort((left, right) =>
  860. left.name.localeCompare(right.name),
  861. );
  862. for (const entry of entries) {
  863. const entryPath = join(rootDir, entry.name);
  864. const entryRelativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;
  865. if (entry.isDirectory()) {
  866. const dirStat = await stat(entryPath);
  867. hash.update(`dir:${entryRelativePath}:${dirStat.mode & 0o777}\n`);
  868. await hashDirectoryContent(hash, entryPath, entryRelativePath);
  869. continue;
  870. }
  871. if (entry.isFile()) {
  872. await hashFileContent(hash, entryPath, entryRelativePath);
  873. continue;
  874. }
  875. throw new Error(`Unsupported test fixture entry: ${entryPath}`);
  876. }
  877. }
  878. async function computePathContentSha256(path: string): Promise<string> {
  879. const hash = createHash("sha256");
  880. const pathStat = await stat(path);
  881. if (pathStat.isDirectory()) {
  882. hash.update("root:dir\n");
  883. await hashDirectoryContent(hash, path);
  884. } else if (pathStat.isFile()) {
  885. hash.update("root:file\n");
  886. await hashFileContent(hash, path, "root-file");
  887. } else {
  888. throw new Error(`Unsupported test fixture path: ${path}`);
  889. }
  890. return hash.digest("hex");
  891. }
  892. function toVersionedArtifactRequestPath(artifactPath: string): string {
  893. return `/${ZCODE_VERSION}/${artifactPath}`;
  894. }
  895. function toComponentArtifactRequestPath(artifactPath: string): string {
  896. return `/${artifactPath}`;
  897. }
  898. async function createStaticFileServer(
  899. rootDir: string,
  900. options?: {
  901. stalledPaths?: string[];
  902. responseGates?: ReadonlyMap<string, Promise<void>>;
  903. },
  904. ): Promise<{
  905. baseUrl: string;
  906. close(): Promise<void>;
  907. getRequestCount(path: string): number;
  908. }> {
  909. const requestCounts = new Map<string, number>();
  910. const server = createServer(async (req, res) => {
  911. const url = new URL(req.url ?? "/", "http://127.0.0.1");
  912. const encodedRelativePath = url.pathname.replace(/^\/+/, "");
  913. // Bugfix: 客户端组件 URL 现在会对路径段做编码(如 + -> %2B)。
  914. // 测试文件路径是原始文件名,需要先 decode 再命中本地文件系统。
  915. const relativePath = decodeURI(encodedRelativePath);
  916. requestCounts.set(relativePath, (requestCounts.get(relativePath) ?? 0) + 1);
  917. if (options?.stalledPaths?.includes(`/${relativePath}`)) {
  918. res.statusCode = 200;
  919. res.write("{");
  920. return;
  921. }
  922. await options?.responseGates?.get(`/${relativePath}`);
  923. try {
  924. const content = await readFile(join(rootDir, relativePath));
  925. res.statusCode = 200;
  926. res.end(content);
  927. } catch {
  928. res.statusCode = 404;
  929. res.end("not found");
  930. }
  931. });
  932. await new Promise<void>((resolve) => {
  933. server.listen(0, "127.0.0.1", () => resolve());
  934. });
  935. const { port } = server.address() as AddressInfo;
  936. return {
  937. baseUrl: `http://127.0.0.1:${port}`,
  938. close: () =>
  939. new Promise((resolve, reject) => {
  940. server.close((error) => {
  941. if (error) {
  942. reject(error);
  943. return;
  944. }
  945. resolve();
  946. });
  947. }),
  948. getRequestCount(path: string) {
  949. return requestCounts.get(path.replace(/^\/+/, "")) ?? 0;
  950. },
  951. };
  952. }
  953. const tempDirs: string[] = [];
  954. const originalCwd = process.cwd();
  955. const originalRemoteDevAgentBundleEnv = process.env.ZCODE_REMOTE_DEV_AGENT_BUNDLE;
  956. const originalZCodeRuntimeEnv = process.env[ZCODE_RUNTIME_ENV_KEY];
  957. const DEV_CLI_BUNDLE_TEST_SUFFIX = join(
  958. "apps",
  959. "zcode-cli",
  960. "packages",
  961. "cli",
  962. "dist",
  963. "zcode.cjs",
  964. );
  965. afterEach(async () => {
  966. process.chdir(originalCwd);
  967. if (originalRemoteDevAgentBundleEnv === undefined) {
  968. delete process.env.ZCODE_REMOTE_DEV_AGENT_BUNDLE;
  969. } else {
  970. process.env.ZCODE_REMOTE_DEV_AGENT_BUNDLE = originalRemoteDevAgentBundleEnv;
  971. }
  972. if (originalZCodeRuntimeEnv === undefined) {
  973. delete process.env[ZCODE_RUNTIME_ENV_KEY];
  974. } else {
  975. process.env[ZCODE_RUNTIME_ENV_KEY] = originalZCodeRuntimeEnv;
  976. }
  977. await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
  978. });
  979. describe("deployServer legacy agent node-script bundle deployment", () => {
  980. it("调用方已串行化部署时不创建远端 install-root lock", async () => {
  981. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  982. tempDirs.push(rootDir);
  983. const mockCdnDir = join(rootDir, "mock-cdn");
  984. await stageRemoteRuntimeRelease(mockCdnDir);
  985. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, join(mockCdnDir, "releases"));
  986. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  987. addMatchingGlmAndServerArtifactIdentities(remoteFiles, manifest, "linux-arm64");
  988. const backend = new FakeRemoteBackend(remoteFiles);
  989. const deployed = await deployServer(
  990. backend,
  991. { platform: "linux", arch: "arm64" },
  992. {
  993. force: false,
  994. mockCdnDir,
  995. deployLockMode: "caller-serialized",
  996. },
  997. );
  998. expect(deployed).toBe(false);
  999. expect(backend.commands.filter((command) => command.endsWith("--version"))).toHaveLength(1);
  1000. expect(backend.commands.join("\n")).not.toContain(".deploy.lock");
  1001. expect(backend.lockReleaseMarkers).toEqual([]);
  1002. expect(backend.uploads).toEqual([]);
  1003. });
  1004. it("rechecks the server version after acquiring the install-root lock", async () => {
  1005. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  1006. tempDirs.push(rootDir);
  1007. const mockCdnDir = join(rootDir, "mock-cdn");
  1008. await stageRemoteRuntimeRelease(mockCdnDir);
  1009. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, join(mockCdnDir, "releases"));
  1010. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  1011. addMatchingGlmAndServerArtifactIdentities(remoteFiles, manifest, "linux-arm64");
  1012. const backend = new FakeRemoteBackend(remoteFiles, {
  1013. serverVersions: ["previous-version", ZCODE_VERSION],
  1014. });
  1015. const deployed = await deployServer(
  1016. backend,
  1017. { platform: "linux", arch: "arm64" },
  1018. { force: false, mockCdnDir },
  1019. );
  1020. expect(deployed).toBe(false);
  1021. expect(backend.commands.filter((command) => command.endsWith("--version"))).toHaveLength(2);
  1022. expect(backend.commands.join("\n")).toContain(".deploy.lock.holder-");
  1023. expect(backend.lockReleaseMarkers[0]).toMatch(/^zcode-deploy-lock-release:/u);
  1024. expect(backend.uploads).toEqual([]);
  1025. });
  1026. it("waits for the install-root lock before pinning the deployment manifest", async () => {
  1027. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  1028. tempDirs.push(rootDir);
  1029. const mockCdnDir = join(rootDir, "mock-cdn");
  1030. const cdnRoot = join(rootDir, "cdn");
  1031. const remoteCacheDir = join(rootDir, "remote-cache");
  1032. await stageRemoteRuntimeRelease(mockCdnDir);
  1033. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  1034. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  1035. addMatchingGlmAndServerArtifactIdentities(remoteFiles, manifest, "linux-arm64");
  1036. let releaseLockAcquire!: () => void;
  1037. const lockAcquireGate = new Promise<void>((resolve) => {
  1038. releaseLockAcquire = resolve;
  1039. });
  1040. const backend = new FakeRemoteBackend(remoteFiles, { lockAcquireGate });
  1041. const cdnServer = await createStaticFileServer(cdnRoot);
  1042. const manifestPath = `/${ZCODE_VERSION}/manifest-linux-arm64.json`;
  1043. try {
  1044. const deployPromise = deployServer(
  1045. backend,
  1046. { platform: "linux", arch: "arm64" },
  1047. { remoteCdnBaseUrl: cdnServer.baseUrl, remoteCacheDir },
  1048. );
  1049. await vi.waitFor(() => {
  1050. expect(backend.commands.some((command) => command.includes(".deploy.lock"))).toBe(true);
  1051. });
  1052. // Bugfix:deploy lock 等待期间不能提前固定可能过期的 manifest;
  1053. // manifest deadline 必须从本次 owner 真正获锁后开始参与部署事务。
  1054. expect(cdnServer.getRequestCount(manifestPath)).toBe(0);
  1055. releaseLockAcquire();
  1056. await expect(deployPromise).resolves.toBe(false);
  1057. expect(cdnServer.getRequestCount(manifestPath)).toBe(1);
  1058. } finally {
  1059. releaseLockAcquire();
  1060. await cdnServer.close();
  1061. }
  1062. });
  1063. it("部署与 lock release 同时失败时应保留两个错误", async () => {
  1064. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  1065. tempDirs.push(rootDir);
  1066. const backend = new FakeRemoteBackend({}, { lockCloseCode: 91 });
  1067. let caught: unknown;
  1068. try {
  1069. await deployServer(
  1070. backend,
  1071. { platform: "linux", arch: "arm64" },
  1072. { force: true, mockCdnDir: join(rootDir, "missing-cdn") },
  1073. );
  1074. } catch (error) {
  1075. caught = error;
  1076. }
  1077. expect(caught).toBeInstanceOf(AggregateError);
  1078. const errors = (caught as AggregateError).errors as unknown[];
  1079. expect(errors).toHaveLength(2);
  1080. expect(String(errors[0])).toMatch(/release|missing|ENOENT/iu);
  1081. expect(String(errors[1])).toContain("lock-holder release failed (code=91)");
  1082. });
  1083. it("node-runtime 已安装语义版本时应忽略 expectedVersion 的内容 hash 后缀", async () => {
  1084. const backend = new FakeRemoteBackend({
  1085. "~/.zcode/server/node": "node",
  1086. "~/.zcode/server/.asset-components/node-runtime.json":
  1087. '{"id":"node-runtime","version":"v22.16.0+aaaaaaaaaaaa","platformArch":"linux-arm64"}\n',
  1088. });
  1089. const installed: string[] = [];
  1090. const installer: RemoteAssetInstaller = {
  1091. mode: "remote-download",
  1092. async installFile(params) {
  1093. installed.push(params.componentId);
  1094. },
  1095. async installDirectory() {
  1096. throw new Error("installDirectory should not be called");
  1097. },
  1098. };
  1099. await deployNodeRuntime(
  1100. backend,
  1101. {
  1102. platformArch: "linux-arm64",
  1103. installer,
  1104. expectedVersion: "v22.16.0+bbbbbbbbbbbb",
  1105. },
  1106. { log: () => undefined, logWarn: () => undefined },
  1107. );
  1108. expect(installed).toEqual([]);
  1109. });
  1110. it("server 版本相同但远端缺少 node-pty 时应补传", async () => {
  1111. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  1112. tempDirs.push(rootDir);
  1113. const mockCdnDir = join(rootDir, "mock-cdn");
  1114. await stageRemoteRuntimeRelease(mockCdnDir);
  1115. await mkdir(mockCdnDir, { recursive: true });
  1116. const backend = new FakeRemoteBackend();
  1117. const deployed = await deployServer(
  1118. backend,
  1119. { platform: "linux", arch: "arm64" },
  1120. {
  1121. force: false,
  1122. mockCdnDir,
  1123. },
  1124. );
  1125. expect(deployed).toBe(false);
  1126. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/build/Release/pty.node.new")).toBe(
  1127. true,
  1128. );
  1129. });
  1130. it("server 版本相同但远端主 server 缺少 sync channel 时应补传主 server", async () => {
  1131. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  1132. tempDirs.push(rootDir);
  1133. const mockCdnDir = join(rootDir, "mock-cdn");
  1134. await stageRemoteRuntimeRelease(mockCdnDir);
  1135. const backend = new FakeRemoteBackend(createFullyDeployedRemoteFiles("linux-arm64"), {
  1136. commandPlans: [
  1137. {
  1138. matcher: /skill-sync/u,
  1139. exitCode: 2,
  1140. stderrText: "missing required server bundle markers: skill-sync\n",
  1141. },
  1142. ],
  1143. });
  1144. const deployed = await deployServer(
  1145. backend,
  1146. { platform: "linux", arch: "arm64" },
  1147. {
  1148. force: false,
  1149. mockCdnDir,
  1150. },
  1151. );
  1152. expect(deployed).toBe(true);
  1153. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/zcode-server.cjs.new")).toBe(true);
  1154. expect(backend.commands.join("\n")).toContain("skill-sync");
  1155. expect(backend.commands.join("\n")).toContain("mcp-sync");
  1156. expect(backend.commands.join("\n")).toContain("plugin-sync");
  1157. expect(backend.commands.join("\n")).toContain("exportMarketplaceSourceArchive");
  1158. expect(backend.commands.join("\n")).toContain("importMarketplaceSourceArchive");
  1159. expect(backend.commands.join("\n")).toContain("__zcode_rpc_nested_uint8array_v1");
  1160. });
  1161. it("忽略历史资源包选择并部署完整默认远端资源", async () => {
  1162. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  1163. tempDirs.push(rootDir);
  1164. const mockCdnDir = join(rootDir, "mock-cdn");
  1165. await stageRemoteRuntimeRelease(mockCdnDir);
  1166. await mkdir(mockCdnDir, { recursive: true });
  1167. const backend = new FakeRemoteBackend();
  1168. const deployed = await deployServer(
  1169. backend,
  1170. { platform: "linux", arch: "arm64" },
  1171. {
  1172. force: false,
  1173. mockCdnDir,
  1174. resourcePackages: {
  1175. selectedPackageIds: ["server-bundle", "node-runtime", "glm"],
  1176. },
  1177. },
  1178. );
  1179. expect(deployed).toBe(false);
  1180. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/agents/glm/zcode.cjs.new")).toBe(
  1181. true,
  1182. );
  1183. expect(
  1184. backend.uploads.some((upload) =>
  1185. upload.remotePath.includes(`/${retiredProtocolPrefix}/codex`),
  1186. ),
  1187. ).toBe(false);
  1188. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/build/Release/pty.node.new")).toBe(
  1189. true,
  1190. );
  1191. expect(
  1192. backend.uploads.some(
  1193. (upload) => upload.remotePath === `~/.zcode/server/${retiredProxyRuntimeId}.tar.gz`,
  1194. ),
  1195. ).toBe(false);
  1196. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/tools/bfs/bfs.new")).toBe(true);
  1197. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/tools/ripgrep/rg.new")).toBe(true);
  1198. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/tools/ugrep/ugrep.new")).toBe(true);
  1199. });
  1200. it("darwin server 版本相同但远端缺少 spawn-helper 时应补传", async () => {
  1201. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  1202. tempDirs.push(rootDir);
  1203. const mockCdnDir = join(rootDir, "mock-cdn");
  1204. await stageRemoteRuntimeRelease(mockCdnDir, {
  1205. platform: "darwin",
  1206. arch: "arm64",
  1207. });
  1208. await mkdir(mockCdnDir, { recursive: true });
  1209. const backend = new FakeRemoteBackend();
  1210. const deployed = await deployServer(
  1211. backend,
  1212. { platform: "darwin", arch: "arm64" },
  1213. {
  1214. force: false,
  1215. mockCdnDir,
  1216. },
  1217. );
  1218. expect(deployed).toBe(false);
  1219. expect(
  1220. hasUploadForStagingTarget(backend, "~/.zcode/server/build/Release/spawn-helper.new"),
  1221. ).toBe(true);
  1222. expect(
  1223. backend.uploads.some((upload) => upload.remotePath.includes("~/.zcode/server/tools/bfs/")),
  1224. ).toBe(false);
  1225. expect(
  1226. backend.uploads.some((upload) => upload.remotePath.includes("~/.zcode/server/tools/ugrep/")),
  1227. ).toBe(false);
  1228. });
  1229. it("默认部署只处理 ZCode Agent,旧 node-script meta 不再阻断", async () => {
  1230. const backend = new FakeRemoteBackend();
  1231. const installedFiles: string[] = [];
  1232. const installedDirectories: Array<{
  1233. componentId: string;
  1234. remoteDir: string;
  1235. sourceRelativePath: string;
  1236. }> = [];
  1237. const installer: RemoteAssetInstaller = {
  1238. mode: "remote-download",
  1239. async installFile({ componentId, remotePath }) {
  1240. installedFiles.push(`${componentId}:${remotePath}`);
  1241. },
  1242. async installDirectory({ componentId, remoteDir, sourceRelativePath }) {
  1243. installedDirectories.push({
  1244. componentId,
  1245. remoteDir,
  1246. sourceRelativePath,
  1247. });
  1248. },
  1249. };
  1250. await deployZCodeAgentRuntime(
  1251. backend,
  1252. { platform: "linux", arch: "arm64" },
  1253. {
  1254. platformArch: "linux-arm64",
  1255. installer,
  1256. },
  1257. { log: () => undefined, logWarn: () => undefined },
  1258. );
  1259. expect(installedFiles).toEqual(["glm:~/.zcode/server/agents/glm/zcode.cjs"]);
  1260. expect(installedDirectories).toEqual([
  1261. {
  1262. componentId: "glm",
  1263. remoteDir: "~/.zcode/server/agents/glm/packages",
  1264. sourceRelativePath: "glm/linux-arm64/packages",
  1265. },
  1266. ]);
  1267. expect(
  1268. backend.uploads.some(
  1269. (upload) => upload.remotePath === "~/.zcode/server/agents/glm/zcode-agent.new",
  1270. ),
  1271. ).toBe(false);
  1272. expect(
  1273. backend.commands.some(
  1274. (command) =>
  1275. command.includes(`/.zcode/server/agents/${retiredProtocolPrefix}/.version`) &&
  1276. command.includes(LEGACY_REMOTE_TEST_AGENT_RUNTIME.claude.version),
  1277. ),
  1278. ).toBe(false);
  1279. });
  1280. it("强制部署 ZCode Agent 时应要求 installer 刷新 glm 缓存", async () => {
  1281. const backend = new FakeRemoteBackend();
  1282. const installRequests: Array<{
  1283. componentId: string;
  1284. forceRefresh?: boolean;
  1285. kind: "directory" | "file";
  1286. }> = [];
  1287. const installer: RemoteAssetInstaller = {
  1288. mode: "remote-download",
  1289. async installFile({ componentId, forceRefresh }) {
  1290. installRequests.push({ componentId, forceRefresh, kind: "file" });
  1291. },
  1292. async installDirectory({ componentId, forceRefresh }) {
  1293. installRequests.push({ componentId, forceRefresh, kind: "directory" });
  1294. },
  1295. };
  1296. await deployZCodeAgentRuntime(
  1297. backend,
  1298. { platform: "linux", arch: "arm64" },
  1299. {
  1300. platformArch: "linux-arm64",
  1301. installer,
  1302. force: true,
  1303. },
  1304. { log: () => undefined, logWarn: () => undefined },
  1305. );
  1306. expect(installRequests).toEqual([
  1307. { componentId: "glm", forceRefresh: true, kind: "file" },
  1308. { componentId: "glm", forceRefresh: true, kind: "directory" },
  1309. ]);
  1310. });
  1311. it("WSL 部署 ZCode Agent wrapper 时应走上传避免 shell 提前展开", async () => {
  1312. const backend = new FakeWslRemoteBackend();
  1313. const installedFiles: string[] = [];
  1314. const installedDirectories: string[] = [];
  1315. const installer: RemoteAssetInstaller = {
  1316. mode: "remote-download",
  1317. async installFile({ componentId, remotePath }) {
  1318. installedFiles.push(`${componentId}:${remotePath}`);
  1319. },
  1320. async installDirectory({ componentId, remoteDir }) {
  1321. installedDirectories.push(`${componentId}:${remoteDir}`);
  1322. },
  1323. };
  1324. await deployZCodeAgentRuntime(
  1325. backend,
  1326. { platform: "linux", arch: "arm64" },
  1327. {
  1328. platformArch: "linux-arm64",
  1329. installer,
  1330. },
  1331. { log: () => undefined, logWarn: () => undefined },
  1332. );
  1333. const wrapperTempPath = `~/.zcode/server/agents/glm/${REMOTE_AGENT_WRAPPER_FILE_NAME}.new`;
  1334. expect(backend.uploads.map((upload) => upload.remotePath)).toContain(wrapperTempPath);
  1335. expect(backend.remoteFiles.get(wrapperTempPath)).toBe(buildRemoteAgentBundleWrapper("glm"));
  1336. expect(backend.remoteFiles.get(wrapperTempPath)).toContain('"$runtime_root/node"');
  1337. expect(installedDirectories).toEqual(["glm:~/.zcode/server/agents/glm/packages"]);
  1338. expect(
  1339. backend.commands.some(
  1340. (command) =>
  1341. command.includes(`printf %s`) && command.includes(REMOTE_AGENT_WRAPPER_FILE_NAME),
  1342. ),
  1343. ).toBe(false);
  1344. });
  1345. it("WSL 已有坏 wrapper 时即使版本匹配也应重写", async () => {
  1346. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  1347. remoteFiles[`~/.zcode/server/agents/glm/${REMOTE_AGENT_WRAPPER_FILE_NAME}`] =
  1348. '#!/bin/sh\nset -eu\nruntime_root="/home/dev/.zcode/server"\nexec "/node" "/home/dev/.zcode/server/agents/glm/zcode.cjs" ""\n';
  1349. const backend = new FakeWslRemoteBackend(remoteFiles);
  1350. const installedFiles: string[] = [];
  1351. const installedDirectories: string[] = [];
  1352. const installer: RemoteAssetInstaller = {
  1353. mode: "remote-download",
  1354. async installFile({ componentId, remotePath }) {
  1355. installedFiles.push(`${componentId}:${remotePath}`);
  1356. },
  1357. async installDirectory({ componentId, remoteDir }) {
  1358. installedDirectories.push(`${componentId}:${remoteDir}`);
  1359. },
  1360. };
  1361. await deployZCodeAgentRuntime(
  1362. backend,
  1363. { platform: "linux", arch: "arm64" },
  1364. {
  1365. platformArch: "linux-arm64",
  1366. installer,
  1367. },
  1368. { log: () => undefined, logWarn: () => undefined },
  1369. );
  1370. expect(installedFiles).toEqual(["glm:~/.zcode/server/agents/glm/zcode.cjs"]);
  1371. expect(backend.uploads.map((upload) => upload.remotePath)).toContain(
  1372. `~/.zcode/server/agents/glm/${REMOTE_AGENT_WRAPPER_FILE_NAME}.new`,
  1373. );
  1374. expect(installedDirectories).toEqual(["glm:~/.zcode/server/agents/glm/packages"]);
  1375. });
  1376. it("ZCode Agent 版本匹配但远端缺 builtin plugin 资产时应复用 cache 补部署 packages", async () => {
  1377. const remoteOfficialPluginDir = "~/.zcode/server/agents/glm/packages";
  1378. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  1379. remoteFiles[remoteOfficialPluginDir] = "directory marker";
  1380. delete remoteFiles[
  1381. "~/.zcode/server/agents/glm/packages/skill-creator-plugin/.zcode-plugin/plugin.json"
  1382. ];
  1383. // SSH / Docker backend 的 exists 契约只检查普通文件,目录即使存在也会返回 false。
  1384. const backend = new FakeFileOnlyExistsRemoteBackend(remoteFiles, [remoteOfficialPluginDir]);
  1385. const installRequests: Array<{
  1386. componentId: string;
  1387. forceRefresh?: boolean;
  1388. kind: "directory" | "file";
  1389. remotePath?: string;
  1390. remoteDir?: string;
  1391. }> = [];
  1392. const installer: RemoteAssetInstaller = {
  1393. mode: "remote-download",
  1394. async installFile({ componentId, forceRefresh, remotePath }) {
  1395. installRequests.push({
  1396. componentId,
  1397. forceRefresh,
  1398. kind: "file",
  1399. remotePath,
  1400. });
  1401. },
  1402. async installDirectory({ componentId, forceRefresh, remoteDir }) {
  1403. installRequests.push({
  1404. componentId,
  1405. forceRefresh,
  1406. kind: "directory",
  1407. remoteDir,
  1408. });
  1409. },
  1410. };
  1411. await deployZCodeAgentRuntime(
  1412. backend,
  1413. { platform: "linux", arch: "arm64" },
  1414. {
  1415. platformArch: "linux-arm64",
  1416. installer,
  1417. },
  1418. { log: () => undefined, logWarn: () => undefined },
  1419. );
  1420. expect(installRequests).toEqual([
  1421. {
  1422. componentId: "glm",
  1423. forceRefresh: false,
  1424. kind: "file",
  1425. remotePath: "~/.zcode/server/agents/glm/zcode.cjs",
  1426. },
  1427. {
  1428. componentId: "glm",
  1429. forceRefresh: false,
  1430. kind: "directory",
  1431. remoteDir: "~/.zcode/server/agents/glm/packages",
  1432. },
  1433. ]);
  1434. const permissionRepairCommand = backend.commands.find((command) =>
  1435. command.includes("command chmod -R u+rwX"),
  1436. );
  1437. expect(permissionRepairCommand).toEqual(expect.stringContaining("if [ -d "));
  1438. expect(permissionRepairCommand).toContain("/.zcode/server/agents/glm/packages");
  1439. expect(permissionRepairCommand).not.toContain("/.zcode/plugins");
  1440. });
  1441. it("GLM 制品 hash 和 builtin plugin 资产都匹配时不应修复权限", async () => {
  1442. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  1443. remoteFiles["~/.zcode/server/agents/glm/.version"] = "旧版本标签\n";
  1444. remoteFiles["~/.zcode/server/.asset-components/glm.json"] = JSON.stringify({
  1445. id: "glm",
  1446. version: "旧版本标签",
  1447. sha256: TEST_GLM_ARTIFACT_SHA256,
  1448. platformArch: "linux-arm64",
  1449. });
  1450. const backend = new FakeRemoteBackend(remoteFiles);
  1451. const installRequests: string[] = [];
  1452. const installer: RemoteAssetInstaller = {
  1453. mode: "remote-download",
  1454. async resolveComponentSha256() {
  1455. return TEST_GLM_ARTIFACT_SHA256;
  1456. },
  1457. async installFile({ componentId, remotePath }) {
  1458. installRequests.push(`${componentId}:file:${remotePath}`);
  1459. },
  1460. async installDirectory({ componentId, remoteDir }) {
  1461. installRequests.push(`${componentId}:directory:${remoteDir}`);
  1462. },
  1463. };
  1464. await deployZCodeAgentRuntime(
  1465. backend,
  1466. { platform: "linux", arch: "arm64" },
  1467. {
  1468. platformArch: "linux-arm64",
  1469. installer,
  1470. },
  1471. { log: () => undefined, logWarn: () => undefined },
  1472. );
  1473. expect(installRequests).toEqual([]);
  1474. expect(backend.commands.some((command) => command.includes("command chmod -R u+rwX"))).toBe(
  1475. false,
  1476. );
  1477. });
  1478. it("GLM 版本相同但制品 hash 变化时应重新部署并修复旧目录权限", async () => {
  1479. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  1480. remoteFiles["~/.zcode/server/.asset-components/glm.json"] = JSON.stringify({
  1481. id: "glm",
  1482. version: ZCODE_AGENT_RUNTIME.version,
  1483. sha256: "b".repeat(64),
  1484. platformArch: "linux-arm64",
  1485. });
  1486. const backend = new FakeRemoteBackend(remoteFiles);
  1487. const installRequests: Array<{
  1488. componentId: string;
  1489. forceRefresh?: boolean;
  1490. kind: "directory" | "file";
  1491. remotePath?: string;
  1492. remoteDir?: string;
  1493. }> = [];
  1494. const installer: RemoteAssetInstaller = {
  1495. mode: "remote-download",
  1496. async resolveComponentSha256() {
  1497. return TEST_GLM_ARTIFACT_SHA256;
  1498. },
  1499. async installFile({ componentId, forceRefresh, remotePath }) {
  1500. installRequests.push({
  1501. componentId,
  1502. forceRefresh,
  1503. kind: "file",
  1504. remotePath,
  1505. });
  1506. },
  1507. async installDirectory({ componentId, forceRefresh, remoteDir }) {
  1508. expect(backend.commands.some((command) => command.includes("command chmod -R u+rwX"))).toBe(
  1509. true,
  1510. );
  1511. installRequests.push({
  1512. componentId,
  1513. forceRefresh,
  1514. kind: "directory",
  1515. remoteDir,
  1516. });
  1517. },
  1518. };
  1519. await deployZCodeAgentRuntime(
  1520. backend,
  1521. { platform: "linux", arch: "arm64" },
  1522. {
  1523. platformArch: "linux-arm64",
  1524. installer,
  1525. },
  1526. { log: () => undefined, logWarn: () => undefined },
  1527. );
  1528. const permissionRepairCommandIndex = backend.commands.findIndex((command) =>
  1529. command.includes("command chmod -R u+rwX"),
  1530. );
  1531. expect(permissionRepairCommandIndex).toBeGreaterThanOrEqual(0);
  1532. expect(backend.commands[permissionRepairCommandIndex]).toContain(
  1533. "/.zcode/server/agents/glm/packages",
  1534. );
  1535. expect(installRequests).toEqual([
  1536. {
  1537. componentId: "glm",
  1538. forceRefresh: false,
  1539. kind: "file",
  1540. remotePath: "~/.zcode/server/agents/glm/zcode.cjs",
  1541. },
  1542. {
  1543. componentId: "glm",
  1544. forceRefresh: false,
  1545. kind: "directory",
  1546. remoteDir: "~/.zcode/server/agents/glm/packages",
  1547. },
  1548. ]);
  1549. });
  1550. it("ZCode Agent 升级时权限修复失败仍应尝试替换 packages", async () => {
  1551. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  1552. remoteFiles["~/.zcode/server/agents/glm/.version"] = "3.3.3\n";
  1553. const backend = new FakeRemoteBackend(remoteFiles, {
  1554. commandPlans: [
  1555. {
  1556. matcher: /command chmod -R u\+rwX/u,
  1557. exitCode: 1,
  1558. stderrText: "chmod: permission denied",
  1559. },
  1560. ],
  1561. });
  1562. const installRequests: string[] = [];
  1563. const installer: RemoteAssetInstaller = {
  1564. mode: "remote-download",
  1565. async installFile({ componentId, remotePath }) {
  1566. installRequests.push(`${componentId}:file:${remotePath}`);
  1567. },
  1568. async installDirectory({ componentId, remoteDir }) {
  1569. installRequests.push(`${componentId}:directory:${remoteDir}`);
  1570. },
  1571. };
  1572. const warnings: string[] = [];
  1573. await deployZCodeAgentRuntime(
  1574. backend,
  1575. { platform: "linux", arch: "arm64" },
  1576. {
  1577. platformArch: "linux-arm64",
  1578. installer,
  1579. },
  1580. { log: () => undefined, logWarn: (message) => warnings.push(message) },
  1581. );
  1582. expect(warnings.some((message) => message.includes("修复旧 builtin plugin 目录权限失败"))).toBe(
  1583. true,
  1584. );
  1585. expect(installRequests).toEqual([
  1586. "glm:directory:~/.zcode/server/agents/glm/packages",
  1587. "glm:file:~/.zcode/server/agents/glm/zcode.cjs",
  1588. ]);
  1589. });
  1590. it("ZCode Agent 升级时 chmod 失败后 packages 替换失败不应继续更新 bundle", async () => {
  1591. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  1592. remoteFiles["~/.zcode/server/agents/glm/.version"] = "3.3.3\n";
  1593. const backend = new FakeRemoteBackend(remoteFiles, {
  1594. commandPlans: [
  1595. {
  1596. matcher: /command chmod -R u\+rwX/u,
  1597. exitCode: 1,
  1598. stderrText: "chmod: permission denied",
  1599. },
  1600. ],
  1601. });
  1602. const installRequests: string[] = [];
  1603. const installer: RemoteAssetInstaller = {
  1604. mode: "remote-download",
  1605. async installFile({ componentId, remotePath }) {
  1606. installRequests.push(`${componentId}:file:${remotePath}`);
  1607. },
  1608. async installDirectory({ componentId, remoteDir }) {
  1609. installRequests.push(`${componentId}:directory:${remoteDir}`);
  1610. throw new Error("packages replace failed");
  1611. },
  1612. };
  1613. await expect(
  1614. deployZCodeAgentRuntime(
  1615. backend,
  1616. { platform: "linux", arch: "arm64" },
  1617. {
  1618. platformArch: "linux-arm64",
  1619. installer,
  1620. },
  1621. { log: () => undefined, logWarn: () => undefined },
  1622. ),
  1623. ).rejects.toThrow("packages replace failed");
  1624. expect(installRequests).toEqual(["glm:directory:~/.zcode/server/agents/glm/packages"]);
  1625. });
  1626. it("开发态官方插件资产必须包含 Browser client、effective docs 与 document judge agent", () => {
  1627. // 回归原因:开发态远程上传曾漏掉 scripts,node_repl 能启动但首次 Browser bootstrap 必然导入失败。
  1628. expect(REMOTE_AGENT_OFFICIAL_PLUGIN_INCLUDED_TOP_LEVEL_PATHS).toEqual(
  1629. expect.arrayContaining(["agents", "dist", "docs", "scripts", "skills"]),
  1630. );
  1631. expect(REMOTE_AGENT_OFFICIAL_PLUGIN_REQUIRED_RELATIVE_PATHS).toEqual(
  1632. expect.arrayContaining([
  1633. ...BROWSER_USE_REQUIRED_RELATIVE_PATHS,
  1634. "image-search-plugin/.mcp.json",
  1635. "documents-plugin/agents/visual-judge.md",
  1636. "documents-plugin/skills/docx/SKILL.md",
  1637. "pdf-plugin/agents/visual-judge.md",
  1638. "pdf-plugin/skills/pdf/SKILL.md",
  1639. "presentations-plugin/agents/visual-judge.md",
  1640. "presentations-plugin/skills/pptx/SKILL.md",
  1641. "spreadsheets-plugin/agents/visual-judge.md",
  1642. "spreadsheets-plugin/skills/xlsx/SKILL.md",
  1643. ]),
  1644. );
  1645. });
  1646. it("开发态缺少 Browser client 时应在上传前拒绝残缺插件", async () => {
  1647. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-dev-agent-missing-browser-client-"));
  1648. tempDirs.push(rootDir);
  1649. const repoDir = join(rootDir, "z-code");
  1650. const cliBundlePath = join(
  1651. repoDir,
  1652. "apps",
  1653. "zcode-cli",
  1654. "packages",
  1655. "cli",
  1656. "dist",
  1657. "zcode.cjs",
  1658. );
  1659. await mkdir(dirname(cliBundlePath), { recursive: true });
  1660. await writeFile(cliBundlePath, "console.log('dev zcode agent');\n", "utf8");
  1661. await writeTestOfficialPluginPackages(repoDir);
  1662. await rm(
  1663. join(
  1664. repoDir,
  1665. "apps",
  1666. "zcode-cli",
  1667. "packages",
  1668. "browser-use-plugin",
  1669. "scripts",
  1670. "browser-client.mjs",
  1671. ),
  1672. );
  1673. process.chdir(repoDir);
  1674. process.env.ZCODE_REMOTE_DEV_AGENT_BUNDLE = "1";
  1675. process.env[ZCODE_RUNTIME_ENV_KEY] = "development";
  1676. const backend = new FakeRemoteBackend();
  1677. const installer: RemoteAssetInstaller = {
  1678. mode: "remote-download",
  1679. async installFile() {
  1680. throw new Error("installFile should not be called");
  1681. },
  1682. async installDirectory() {
  1683. throw new Error("installDirectory should not be called");
  1684. },
  1685. };
  1686. await expect(
  1687. deployZCodeAgentRuntime(
  1688. backend,
  1689. { platform: "linux", arch: "arm64" },
  1690. {
  1691. platformArch: "linux-arm64",
  1692. installer,
  1693. selectedResourcePackageIds: ["glm"],
  1694. },
  1695. { log: () => undefined, logWarn: () => undefined },
  1696. ),
  1697. ).rejects.toThrow(/missing official plugin required asset.*browser-client\.mjs/iu);
  1698. expect(backend.uploads).toEqual([]);
  1699. });
  1700. it("开发态 SSH 部署应上传本地 zcode.cjs 并生成远端 wrapper", async () => {
  1701. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-dev-agent-"));
  1702. tempDirs.push(rootDir);
  1703. const repoDir = join(rootDir, "z-code");
  1704. const cliBundlePath = join(
  1705. repoDir,
  1706. "apps",
  1707. "zcode-cli",
  1708. "packages",
  1709. "cli",
  1710. "dist",
  1711. "zcode.cjs",
  1712. );
  1713. await mkdir(dirname(cliBundlePath), { recursive: true });
  1714. await writeFile(cliBundlePath, "console.log('dev zcode agent');\n", "utf8");
  1715. await writeTestOfficialPluginPackages(repoDir);
  1716. process.chdir(repoDir);
  1717. process.env.ZCODE_REMOTE_DEV_AGENT_BUNDLE = "1";
  1718. process.env[ZCODE_RUNTIME_ENV_KEY] = "development";
  1719. const backend = new FakeRemoteBackend();
  1720. const installedFiles: string[] = [];
  1721. const installer: RemoteAssetInstaller = {
  1722. mode: "remote-download",
  1723. async resolveComponentVersion() {
  1724. return "cdn-glm-version";
  1725. },
  1726. async installFile({ componentId, remotePath }) {
  1727. installedFiles.push(`${componentId}:${remotePath}`);
  1728. },
  1729. async installDirectory() {
  1730. throw new Error("installDirectory should not be called");
  1731. },
  1732. };
  1733. await deployZCodeAgentRuntime(
  1734. backend,
  1735. { platform: "linux", arch: "arm64" },
  1736. {
  1737. platformArch: "linux-arm64",
  1738. installer,
  1739. selectedResourcePackageIds: ["glm"],
  1740. },
  1741. { log: () => undefined, logWarn: () => undefined },
  1742. );
  1743. expect(installedFiles).toEqual([]);
  1744. const devBundleUpload = backend.uploads.find(
  1745. (upload) =>
  1746. upload.remotePath === "~/.zcode/server/agents/glm/zcode.cjs.new" ||
  1747. upload.remotePath.startsWith("~/.zcode/server/agents/glm/zcode.cjs.new-"),
  1748. );
  1749. expect(devBundleUpload?.localPath.endsWith(DEV_CLI_BUNDLE_TEST_SUFFIX)).toBe(true);
  1750. expect(
  1751. backend.commands.some(
  1752. (command) => command.includes("zcode-agent.new") && command.includes("zcode.cjs"),
  1753. ),
  1754. ).toBe(true);
  1755. expect(backend.commands.some((command) => command.includes(".dev-version"))).toBe(true);
  1756. const officialPluginUpload = backend.uploads.find((upload) =>
  1757. upload.remotePath.includes("/agents/glm/packages.tar.gz-"),
  1758. );
  1759. expect(officialPluginUpload?.remotePath).toMatch(
  1760. /^~\/.zcode\/server\/agents\/glm\/packages\.tar\.gz-[\w-]+$/u,
  1761. );
  1762. expect(
  1763. backend.commands.some(
  1764. (command) =>
  1765. command.includes("tar -xzf") &&
  1766. command.includes("packages.tar.gz") &&
  1767. command.includes("agents/glm/packages.extract-") &&
  1768. command.includes("trap cleanup_staging EXIT"),
  1769. ),
  1770. ).toBe(true);
  1771. const permissionRepairCommandIndex = backend.commands.findIndex((command) =>
  1772. command.includes("command chmod -R u+rwX"),
  1773. );
  1774. const packageExtractCommandIndex = backend.commands.findIndex(
  1775. (command) =>
  1776. command.includes("tar -xzf") &&
  1777. command.includes("packages.tar.gz") &&
  1778. command.includes("agents/glm/packages"),
  1779. );
  1780. expect(permissionRepairCommandIndex).toBeGreaterThanOrEqual(0);
  1781. expect(permissionRepairCommandIndex).toBeLessThan(packageExtractCommandIndex);
  1782. });
  1783. it.each([true, false])(
  1784. "开发态标记相同时按实际 bundle 是否一致决定跳过上传:%s",
  1785. async (bundleMatches) => {
  1786. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-dev-agent-skip-"));
  1787. tempDirs.push(rootDir);
  1788. const repoDir = join(rootDir, "z-code");
  1789. const cliBundlePath = join(
  1790. repoDir,
  1791. "apps",
  1792. "zcode-cli",
  1793. "packages",
  1794. "cli",
  1795. "dist",
  1796. "zcode.cjs",
  1797. );
  1798. await mkdir(dirname(cliBundlePath), { recursive: true });
  1799. await writeFile(cliBundlePath, "console.log('same dev zcode agent');\n", "utf8");
  1800. await writeTestOfficialPluginPackages(repoDir);
  1801. process.chdir(repoDir);
  1802. process.env.ZCODE_REMOTE_DEV_AGENT_BUNDLE = "1";
  1803. process.env[ZCODE_RUNTIME_ENV_KEY] = "development";
  1804. const devVersion = await computeDevelopmentAgentAssetsSha256ForTest(repoDir, cliBundlePath);
  1805. const backend = new FakeRemoteBackend(
  1806. {
  1807. "~/.zcode/server/agents/glm/.version": `${ZCODE_AGENT_RUNTIME.version}\n`,
  1808. "~/.zcode/server/agents/glm/.dev-version": `${devVersion}\n`,
  1809. "~/.zcode/server/agents/glm/zcode-agent": "dev wrapper",
  1810. "~/.zcode/server/agents/glm/zcode.cjs": bundleMatches
  1811. ? "console.log('same dev zcode agent');\n"
  1812. : "old published bundle without PAT support",
  1813. ...Object.fromEntries(
  1814. OFFICIAL_PLUGIN_REQUIRED_RELATIVE_PATHS.map((relativePath) => [
  1815. `~/.zcode/server/agents/glm/packages/${relativePath}`,
  1816. `dev official plugin ${relativePath}`,
  1817. ]),
  1818. ),
  1819. },
  1820. { commandPlans: [{ matcher: /createHash/, exitCode: bundleMatches ? 0 : 1 }] },
  1821. );
  1822. const installedFiles: string[] = [];
  1823. const installer: RemoteAssetInstaller = {
  1824. mode: "remote-download",
  1825. async resolveComponentVersion() {
  1826. return "cdn-glm-version";
  1827. },
  1828. async installFile({ componentId, remotePath }) {
  1829. installedFiles.push(`${componentId}:${remotePath}`);
  1830. },
  1831. async installDirectory() {
  1832. throw new Error("installDirectory should not be called");
  1833. },
  1834. };
  1835. await deployZCodeAgentRuntime(
  1836. backend,
  1837. { platform: "linux", arch: "arm64" },
  1838. {
  1839. platformArch: "linux-arm64",
  1840. installer,
  1841. selectedResourcePackageIds: ["glm"],
  1842. },
  1843. { log: () => undefined, logWarn: () => undefined },
  1844. );
  1845. expect(installedFiles).toEqual([]);
  1846. expect(backend.uploads.some((upload) => upload.remotePath.endsWith("zcode.cjs.new"))).toBe(
  1847. !bundleMatches,
  1848. );
  1849. expect(backend.commands.some((command) => command.includes("command chmod -R u+rwX"))).toBe(
  1850. !bundleMatches,
  1851. );
  1852. },
  1853. );
  1854. it("darwin 远端强制部署时应上传 node-pty 的 spawn-helper", async () => {
  1855. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  1856. tempDirs.push(rootDir);
  1857. const mockCdnDir = join(rootDir, "mock-cdn");
  1858. await stageRemoteRuntimeRelease(mockCdnDir, {
  1859. platform: "darwin",
  1860. arch: "arm64",
  1861. });
  1862. await mkdir(mockCdnDir, { recursive: true });
  1863. const backend = new FakeRemoteBackend();
  1864. await deployServer(
  1865. backend,
  1866. { platform: "darwin", arch: "arm64" },
  1867. {
  1868. force: true,
  1869. mockCdnDir,
  1870. },
  1871. );
  1872. expect(
  1873. hasUploadForStagingTarget(backend, "~/.zcode/server/build/Release/spawn-helper.new"),
  1874. ).toBe(true);
  1875. });
  1876. it("远端覆盖替换应绕过 shell alias/function 并强制覆盖", async () => {
  1877. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  1878. tempDirs.push(rootDir);
  1879. const mockCdnDir = join(rootDir, "mock-cdn");
  1880. await stageRemoteRuntimeRelease(mockCdnDir);
  1881. await mkdir(mockCdnDir, { recursive: true });
  1882. const backend = new FakeRemoteBackend();
  1883. await deployServer(
  1884. backend,
  1885. { platform: "linux", arch: "arm64" },
  1886. {
  1887. force: true,
  1888. mockCdnDir,
  1889. },
  1890. );
  1891. const replaceCommands = backend.commands.filter(
  1892. (command) => command.includes(".new") && command.includes("mv"),
  1893. );
  1894. expect(replaceCommands.length).toBeGreaterThan(0);
  1895. for (const command of replaceCommands) {
  1896. expect(command).toContain("command mv -f ");
  1897. expect(command).not.toMatch(/(^|&& )mv /);
  1898. }
  1899. const chmodCommands = replaceCommands.filter((command) => command.includes("chmod"));
  1900. expect(chmodCommands.length).toBeGreaterThan(0);
  1901. for (const command of chmodCommands) {
  1902. expect(command).toContain("command chmod +x ");
  1903. expect(command).not.toMatch(/(^|&& )chmod \+x /);
  1904. }
  1905. });
  1906. it("replace 命令在存在同名 shell function 时仍应执行真实 mv/chmod", async () => {
  1907. if (process.platform === "win32") {
  1908. return;
  1909. }
  1910. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-replace-cmd-"));
  1911. tempDirs.push(rootDir);
  1912. const sourcePath = join(rootDir, "node.new");
  1913. const targetPath = join(rootDir, "node");
  1914. await writeFile(sourcePath, "new-runtime", "utf8");
  1915. await writeFile(targetPath, "old-runtime", "utf8");
  1916. const replaceCommand = buildRemoteExecutableReplaceCommand(sourcePath, targetPath);
  1917. execFileSync(
  1918. "sh",
  1919. [
  1920. "-lc",
  1921. [
  1922. "set -eu",
  1923. // Bugfix: 这里故意定义同名 shell function 模拟远端污染环境。
  1924. // 如果 replace 命令没有使用 `command` 前缀,会命中函数并失败。
  1925. "mv(){ echo SHOULD_NOT_CALL_MV_FUNCTION >&2; return 31; }",
  1926. "chmod(){ echo SHOULD_NOT_CALL_CHMOD_FUNCTION >&2; return 32; }",
  1927. replaceCommand,
  1928. ].join("\n"),
  1929. ],
  1930. { stdio: "pipe" },
  1931. );
  1932. await expect(stat(sourcePath)).rejects.toThrow();
  1933. expect(await readFile(targetPath, "utf8")).toBe("new-runtime");
  1934. expect((await stat(targetPath)).mode & 0o111).not.toBe(0);
  1935. });
  1936. it("远端 replace 命令非 0 退出时应立即中断部署", async () => {
  1937. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  1938. tempDirs.push(rootDir);
  1939. const mockCdnDir = join(rootDir, "mock-cdn");
  1940. await stageRemoteRuntimeRelease(mockCdnDir);
  1941. await mkdir(mockCdnDir, { recursive: true });
  1942. const backend = new FakeRemoteBackend(
  1943. {},
  1944. {
  1945. commandPlans: [
  1946. {
  1947. matcher: /command mv -f .*zcode-server\.cjs/,
  1948. exitCode: 23,
  1949. stderrText: "mock mv failed",
  1950. },
  1951. ],
  1952. },
  1953. );
  1954. await expect(
  1955. deployServer(
  1956. backend,
  1957. { platform: "linux", arch: "arm64" },
  1958. {
  1959. force: true,
  1960. mockCdnDir,
  1961. },
  1962. ),
  1963. ).rejects.toThrow(/exit code 23/);
  1964. expect(backend.lockReleaseMarkers[0]).toMatch(/^zcode-deploy-lock-release:/u);
  1965. });
  1966. it("生产态未接入 CDN 下载占位时应抛出明确错误", async () => {
  1967. const backend = new FakeRemoteBackend({
  1968. "~/.zcode/server/agents/codex/.version": "0.0.0\n",
  1969. });
  1970. await expect(
  1971. deployServer(
  1972. backend,
  1973. { platform: "linux", arch: "arm64" },
  1974. {
  1975. force: false,
  1976. remoteCacheDir: "/tmp/zcode-remote-cache",
  1977. },
  1978. ),
  1979. ).rejects.toThrow(
  1980. /require remoteCdnBaseUrl or remoteCdnBaseUrls, remoteCacheDir and platformArch/,
  1981. );
  1982. });
  1983. it("生产态 remoteCdnBaseUrl 固定到旧版本时应前置报错", async () => {
  1984. const backend = new FakeRemoteBackend({
  1985. "~/.zcode/server/agents/codex/.version": "0.0.0\n",
  1986. });
  1987. await expect(
  1988. deployServer(
  1989. backend,
  1990. { platform: "linux", arch: "arm64" },
  1991. {
  1992. force: false,
  1993. remoteCdnBaseUrl:
  1994. "https://cdn.example.com/zcode/electron/releases-sandbox/fix-small-issues/0.2.7",
  1995. remoteCacheDir: "/tmp/zcode-remote-cache",
  1996. },
  1997. ),
  1998. ).rejects.toThrow(/remoteCdnBaseUrl 版本不匹配/);
  1999. });
  2000. it("生产态 manifest 存在时应优先下载组件产物并写入 cache(不走 legacy 整包)", async () => {
  2001. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2002. tempDirs.push(rootDir);
  2003. const mockCdnDir = join(rootDir, "mock-cdn");
  2004. const cdnRoot = join(rootDir, "cdn");
  2005. const remoteCacheDir = join(rootDir, "remote-cache");
  2006. await stageRemoteRuntimeRelease(mockCdnDir);
  2007. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  2008. await stageRemoteAssetArchive(mockCdnDir, cdnRoot);
  2009. const cdnServer = await createStaticFileServer(cdnRoot);
  2010. const glmBundle = manifest.components.find((component) => component.id === "glm");
  2011. if (!glmBundle) {
  2012. throw new Error("missing glm component in staged manifest");
  2013. }
  2014. try {
  2015. const remoteFiles = {
  2016. "~/.zcode/server/agents/codex/.version": "0.0.0\n",
  2017. };
  2018. addMatchingServerBundleArtifactIdentity(remoteFiles, manifest, "linux-arm64");
  2019. const backend = new FakeRemoteBackend(remoteFiles);
  2020. const deployed = await deployServer(
  2021. backend,
  2022. { platform: "linux", arch: "arm64" },
  2023. {
  2024. force: false,
  2025. remoteCdnBaseUrl: cdnServer.baseUrl,
  2026. remoteCacheDir,
  2027. resourcePackages: {
  2028. selectedPackageIds: [`${retiredProtocolPrefix}-codex`, "ripgrep"],
  2029. },
  2030. },
  2031. );
  2032. expect(deployed).toBe(false);
  2033. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/agents/glm/zcode.cjs.new")).toBe(
  2034. true,
  2035. );
  2036. expect(
  2037. backend.uploads.some(
  2038. (upload) => upload.remotePath === "~/.zcode/server/agents/codex.tar.gz",
  2039. ),
  2040. ).toBe(false);
  2041. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/tools/ripgrep/rg.new")).toBe(true);
  2042. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(1);
  2043. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/remote-assets-linux-arm64.tar.gz`)).toBe(
  2044. 0,
  2045. );
  2046. expect(
  2047. cdnServer.getRequestCount(toComponentArtifactRequestPath(glmBundle.artifactPath)),
  2048. ).toBe(1);
  2049. } finally {
  2050. await cdnServer.close();
  2051. }
  2052. });
  2053. it("本地下载后上传通过注入的远程资源网络出口获取 manifest 和组件", async () => {
  2054. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2055. tempDirs.push(rootDir);
  2056. const mockCdnDir = join(rootDir, "mock-cdn");
  2057. const cdnRoot = join(rootDir, "cdn");
  2058. const remoteCacheDir = join(rootDir, "remote-cache");
  2059. await stageRemoteRuntimeRelease(mockCdnDir);
  2060. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  2061. const cdnServer = await createStaticFileServer(cdnRoot);
  2062. const originalFetch = globalThis.fetch.bind(globalThis);
  2063. const remoteAssetFetch = vi.fn<typeof fetch>((input, init) => originalFetch(input, init));
  2064. const directFetch = vi
  2065. .spyOn(globalThis, "fetch")
  2066. .mockRejectedValue(new Error("remote asset direct fetch is forbidden"));
  2067. try {
  2068. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  2069. addMatchingServerBundleArtifactIdentity(remoteFiles, manifest, "linux-arm64");
  2070. const backend = new FakeRemoteBackend(remoteFiles);
  2071. await deployServer(
  2072. backend,
  2073. { platform: "linux", arch: "arm64" },
  2074. {
  2075. remoteAssetNetwork: { fetch: remoteAssetFetch },
  2076. remoteCdnBaseUrl: cdnServer.baseUrl,
  2077. remoteCacheDir,
  2078. },
  2079. );
  2080. expect(directFetch).not.toHaveBeenCalled();
  2081. expect(
  2082. remoteAssetFetch.mock.calls.some(([input]) =>
  2083. String(input).endsWith(`/${ZCODE_VERSION}/manifest-linux-arm64.json`),
  2084. ),
  2085. ).toBe(true);
  2086. const glmComponent = findManifestComponent(manifest, "glm");
  2087. expect(
  2088. remoteAssetFetch.mock.calls.some(([input]) =>
  2089. String(input).endsWith(`/${glmComponent.artifactPath}`),
  2090. ),
  2091. ).toBe(true);
  2092. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/agents/glm/zcode.cjs.new")).toBe(
  2093. true,
  2094. );
  2095. } finally {
  2096. directFetch.mockRestore();
  2097. await cdnServer.close();
  2098. }
  2099. });
  2100. it("远程资源网络出口失败时不回退 global fetch", async () => {
  2101. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2102. tempDirs.push(rootDir);
  2103. const directFetch = vi
  2104. .spyOn(globalThis, "fetch")
  2105. .mockResolvedValue(new Response("unexpected direct response", { status: 200 }));
  2106. const remoteAssetFetch = vi.fn<typeof fetch>(async () => {
  2107. throw new Error("configured proxy unavailable");
  2108. });
  2109. try {
  2110. await expect(
  2111. ensureRemoteReleaseDirFromCdn(
  2112. {
  2113. remoteAssetNetwork: { fetch: remoteAssetFetch },
  2114. remoteCdnBaseUrl: "https://remote-assets.example.test",
  2115. remoteCacheDir: join(rootDir, "remote-cache"),
  2116. version: ZCODE_VERSION,
  2117. platformArch: "linux-arm64",
  2118. componentIds: ["glm"],
  2119. },
  2120. { log: () => undefined, logWarn: () => undefined },
  2121. ),
  2122. ).rejects.toThrow("configured proxy unavailable");
  2123. expect(remoteAssetFetch).toHaveBeenCalled();
  2124. expect(directFetch).not.toHaveBeenCalled();
  2125. } finally {
  2126. directFetch.mockRestore();
  2127. }
  2128. });
  2129. it("mock-cdn 版本目录存在但缺目标平台组件时应回退 CDN cache", async () => {
  2130. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2131. tempDirs.push(rootDir);
  2132. const mockCdnDir = join(rootDir, "mock-cdn");
  2133. const cdnSourceMockCdnDir = join(rootDir, "cdn-source-mock-cdn");
  2134. const cdnRoot = join(rootDir, "cdn");
  2135. const remoteCacheDir = join(rootDir, "remote-cache");
  2136. await stageRemoteRuntimeRelease(mockCdnDir, {
  2137. platform: "linux",
  2138. arch: "arm64",
  2139. });
  2140. await stageRemoteRuntimeRelease(cdnSourceMockCdnDir, {
  2141. platform: "linux",
  2142. arch: "x64",
  2143. });
  2144. await stageRemoteComponentArtifacts(cdnSourceMockCdnDir, cdnRoot, {
  2145. platformKey: "linux-x64",
  2146. });
  2147. const cdnServer = await createStaticFileServer(cdnRoot);
  2148. try {
  2149. const backend = new FakeRemoteBackend();
  2150. const deployed = await deployServer(
  2151. backend,
  2152. { platform: "linux", arch: "x64" },
  2153. {
  2154. force: true,
  2155. mockCdnDir,
  2156. remoteCdnBaseUrl: cdnServer.baseUrl,
  2157. remoteCacheDir,
  2158. },
  2159. );
  2160. const nodeUpload = backend.uploads.find((upload) =>
  2161. upload.remotePath.startsWith("~/.zcode/server/node.new-"),
  2162. );
  2163. expect(deployed).toBe(true);
  2164. expect(nodeUpload?.localPath).toContain(remoteCacheDir);
  2165. expect(nodeUpload?.localPath).not.toContain(mockCdnDir);
  2166. expect(
  2167. cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-x64.json`),
  2168. ).toBeGreaterThan(0);
  2169. } finally {
  2170. await cdnServer.close();
  2171. }
  2172. });
  2173. it("mock manifest 存在但 GLM 文件缺失时应使用 CDN SHA 决策与部署", async () => {
  2174. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2175. tempDirs.push(rootDir);
  2176. const mockCdnDir = join(rootDir, "mock-cdn");
  2177. const cdnSourceDir = join(rootDir, "cdn-source");
  2178. const cdnRoot = join(rootDir, "cdn");
  2179. const remoteCacheDir = join(rootDir, "remote-cache");
  2180. await stageRemoteRuntimeRelease(mockCdnDir);
  2181. const mockManifest = await stageRemoteComponentArtifacts(
  2182. mockCdnDir,
  2183. join(mockCdnDir, "releases"),
  2184. );
  2185. await stageRemoteRuntimeRelease(cdnSourceDir);
  2186. await writeFile(
  2187. join(cdnSourceDir, "releases", ZCODE_VERSION, "glm", "linux-arm64", "zcode.cjs"),
  2188. "new CDN GLM bytes under the same semantic version",
  2189. "utf8",
  2190. );
  2191. const cdnManifest = await stageRemoteComponentArtifacts(cdnSourceDir, cdnRoot);
  2192. const mockGlm = mockManifest.components.find((component) => component.id === "glm");
  2193. const cdnGlm = cdnManifest.components.find((component) => component.id === "glm");
  2194. expect(cdnGlm?.version).toBe(mockGlm?.version);
  2195. expect(cdnGlm?.sha256).not.toBe(mockGlm?.sha256);
  2196. await rm(join(mockCdnDir, "releases", ZCODE_VERSION, "glm", "linux-arm64", "zcode.cjs"));
  2197. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  2198. addMatchingGlmArtifactIdentity(remoteFiles, mockManifest, "linux-arm64");
  2199. const backend = new FakeRemoteBackend(remoteFiles);
  2200. const cdnServer = await createStaticFileServer(cdnRoot);
  2201. try {
  2202. await deployServer(
  2203. backend,
  2204. { platform: "linux", arch: "arm64" },
  2205. {
  2206. mockCdnDir,
  2207. remoteCdnBaseUrl: cdnServer.baseUrl,
  2208. remoteCacheDir,
  2209. },
  2210. );
  2211. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/agents/glm/zcode.cjs.new")).toBe(
  2212. true,
  2213. );
  2214. expect(backend.commands.join("\n")).toContain(cdnGlm?.sha256);
  2215. } finally {
  2216. await cdnServer.close();
  2217. }
  2218. });
  2219. it("本地上传的 GLM hash 变化时不应复用完整的旧语义版本 cache", async () => {
  2220. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2221. tempDirs.push(rootDir);
  2222. const mockCdnDir = join(rootDir, "mock-cdn");
  2223. const cdnRoot = join(rootDir, "cdn");
  2224. const remoteCacheDir = join(rootDir, "remote-cache");
  2225. await stageRemoteRuntimeRelease(mockCdnDir);
  2226. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot, {
  2227. mutateManifest: (sourceManifest) => ({
  2228. ...sourceManifest,
  2229. components: sourceManifest.components.map((component) =>
  2230. component.id === "glm"
  2231. ? { ...component, version: `${component.version}+aaaaaaaaaaaa` }
  2232. : component,
  2233. ),
  2234. }),
  2235. });
  2236. const glmComponent = manifest.components.find((component) => component.id === "glm");
  2237. if (!glmComponent) {
  2238. throw new Error("missing glm component in staged manifest");
  2239. }
  2240. const glmSemanticVersion = glmComponent.version.replace(/\+[a-f0-9]{12,64}$/u, "");
  2241. const staleComponentDir = join(
  2242. remoteCacheDir,
  2243. "components",
  2244. "glm",
  2245. "linux-arm64",
  2246. glmSemanticVersion,
  2247. );
  2248. await mkdir(staleComponentDir, { recursive: true });
  2249. await writeFile(join(staleComponentDir, ".ready"), "ready\n", "utf8");
  2250. await writeFile(join(staleComponentDir, "zcode.cjs"), "stale glm bundle");
  2251. for (const relativePath of OFFICIAL_PLUGIN_REQUIRED_RELATIVE_PATHS) {
  2252. const stalePluginPath = join(staleComponentDir, "packages", ...relativePath.split("/"));
  2253. await mkdir(dirname(stalePluginPath), { recursive: true });
  2254. await writeFile(stalePluginPath, "stale official plugin", "utf8");
  2255. }
  2256. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  2257. addMatchingServerBundleArtifactIdentity(remoteFiles, manifest, "linux-arm64");
  2258. delete remoteFiles[
  2259. "~/.zcode/server/agents/glm/packages/skill-creator-plugin/.zcode-plugin/plugin.json"
  2260. ];
  2261. const cdnServer = await createStaticFileServer(cdnRoot);
  2262. try {
  2263. const backend = new FakeRemoteBackend(remoteFiles);
  2264. const deployed = await deployServer(
  2265. backend,
  2266. { platform: "linux", arch: "arm64" },
  2267. {
  2268. force: false,
  2269. remoteCdnBaseUrl: cdnServer.baseUrl,
  2270. remoteCacheDir,
  2271. },
  2272. );
  2273. expect(deployed).toBe(false);
  2274. expect(
  2275. backend.uploads.some((upload) =>
  2276. upload.remotePath.startsWith("~/.zcode/server/agents/glm/packages.tar.gz-"),
  2277. ),
  2278. ).toBe(true);
  2279. expect(
  2280. cdnServer.getRequestCount(toComponentArtifactRequestPath(glmComponent.artifactPath)),
  2281. ).toBe(1);
  2282. await expect(
  2283. readFile(
  2284. join(
  2285. remoteCacheDir,
  2286. "components",
  2287. "glm",
  2288. "linux-arm64",
  2289. glmComponent.sha256,
  2290. "packages",
  2291. "skill-creator-plugin",
  2292. ".zcode-plugin",
  2293. "plugin.json",
  2294. ),
  2295. "utf8",
  2296. ),
  2297. ).resolves.toContain("glm official plugin");
  2298. await expect(readFile(join(staleComponentDir, "zcode.cjs"), "utf8")).resolves.toBe(
  2299. "stale glm bundle",
  2300. );
  2301. } finally {
  2302. await cdnServer.close();
  2303. }
  2304. });
  2305. it("并发预热复用 release 锁后仍应按当前 required paths 补齐残缺 component cache", async () => {
  2306. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2307. tempDirs.push(rootDir);
  2308. const mockCdnDir = join(rootDir, "mock-cdn");
  2309. const cdnRoot = join(rootDir, "cdn");
  2310. const remoteCacheDir = join(rootDir, "remote-cache");
  2311. await stageRemoteRuntimeRelease(mockCdnDir);
  2312. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot, {
  2313. mutateManifest: (sourceManifest) => ({
  2314. ...sourceManifest,
  2315. components: sourceManifest.components.map((component) =>
  2316. component.id === "glm"
  2317. ? { ...component, version: `${component.version}+bbbbbbbbbbbb` }
  2318. : component,
  2319. ),
  2320. }),
  2321. });
  2322. const glmComponent = manifest.components.find((component) => component.id === "glm");
  2323. if (!glmComponent) {
  2324. throw new Error("missing glm component in staged manifest");
  2325. }
  2326. const glmSemanticVersion = glmComponent.version.replace(/\+[a-f0-9]{12,64}$/u, "");
  2327. const staleComponentDir = join(
  2328. remoteCacheDir,
  2329. "components",
  2330. "glm",
  2331. "linux-arm64",
  2332. glmSemanticVersion,
  2333. );
  2334. await mkdir(staleComponentDir, { recursive: true });
  2335. await writeFile(join(staleComponentDir, ".ready"), "ready\n", "utf8");
  2336. await writeFile(join(staleComponentDir, "zcode.cjs"), "stale glm bundle");
  2337. const requiredReleasePath =
  2338. "glm/linux-arm64/packages/skill-creator-plugin/.zcode-plugin/plugin.json";
  2339. const cdnServer = await createStaticFileServer(cdnRoot);
  2340. try {
  2341. const [releaseDirWithoutRequired, releaseDirWithRequired] = await Promise.all([
  2342. ensureRemoteReleaseDirFromCdn(
  2343. {
  2344. remoteCdnBaseUrl: cdnServer.baseUrl,
  2345. remoteCacheDir,
  2346. version: ZCODE_VERSION,
  2347. platformArch: "linux-arm64",
  2348. componentIds: ["glm"],
  2349. },
  2350. { log: () => {}, logWarn: () => {} },
  2351. ),
  2352. ensureRemoteReleaseDirFromCdn(
  2353. {
  2354. remoteCdnBaseUrl: cdnServer.baseUrl,
  2355. remoteCacheDir,
  2356. version: ZCODE_VERSION,
  2357. platformArch: "linux-arm64",
  2358. componentIds: ["glm"],
  2359. requiredReleasePaths: [requiredReleasePath],
  2360. },
  2361. { log: () => {}, logWarn: () => {} },
  2362. ),
  2363. ]);
  2364. expect(releaseDirWithRequired).toBe(releaseDirWithoutRequired);
  2365. await expect(
  2366. readFile(join(releaseDirWithRequired, requiredReleasePath), "utf8"),
  2367. ).resolves.toContain("glm official plugin");
  2368. expect(
  2369. cdnServer.getRequestCount(toComponentArtifactRequestPath(glmComponent.artifactPath)),
  2370. ).toBe(1);
  2371. } finally {
  2372. await cdnServer.close();
  2373. }
  2374. });
  2375. it("node-runtime manifest version 带内容 hash 时,远端已安装语义版本应继续跳过", async () => {
  2376. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2377. tempDirs.push(rootDir);
  2378. const mockCdnDir = join(rootDir, "mock-cdn");
  2379. const cdnRoot = join(rootDir, "cdn");
  2380. const remoteCacheDir = join(rootDir, "remote-cache");
  2381. await stageRemoteRuntimeRelease(mockCdnDir);
  2382. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot, {
  2383. mutateManifest: (manifest) => ({
  2384. ...manifest,
  2385. components: manifest.components.map((component) =>
  2386. component.id === "node-runtime"
  2387. ? { ...component, version: `${component.version}+aaaaaaaaaaaa` }
  2388. : component,
  2389. ),
  2390. }),
  2391. });
  2392. const cdnServer = await createStaticFileServer(cdnRoot);
  2393. try {
  2394. const remoteFiles = {
  2395. "~/.zcode/server/version.txt": `${ZCODE_VERSION}\n`,
  2396. "~/.zcode/server/node": "node",
  2397. "~/.zcode/server/.asset-components/node-runtime.json":
  2398. '{"id":"node-runtime","version":"24.10.0-node-runtime","platformArch":"linux-arm64"}\n',
  2399. "~/.zcode/server/build/Release/pty.node": "pty",
  2400. "~/.zcode/server/.asset-components/node-pty.json":
  2401. '{"id":"node-pty","version":"1.0.0-node-pty","platformArch":"linux-arm64"}\n',
  2402. };
  2403. addMatchingServerBundleArtifactIdentity(remoteFiles, manifest, "linux-arm64");
  2404. const backend = new FakeRemoteBackend(remoteFiles);
  2405. const deployed = await deployServer(
  2406. backend,
  2407. { platform: "linux", arch: "arm64" },
  2408. {
  2409. force: false,
  2410. remoteCdnBaseUrl: cdnServer.baseUrl,
  2411. remoteCacheDir,
  2412. resourcePackages: {
  2413. selectedPackageIds: ["server-bundle", "node-runtime", "node-pty"],
  2414. },
  2415. },
  2416. );
  2417. expect(deployed).toBe(false);
  2418. expect(backend.commands.join("\n")).not.toContain("node.new");
  2419. expect(backend.commands.join("\n")).not.toContain("node-runtime");
  2420. } finally {
  2421. await cdnServer.close();
  2422. }
  2423. });
  2424. it("ssh remote-download mode installs server assets without local uploads", async () => {
  2425. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2426. tempDirs.push(rootDir);
  2427. const mockCdnDir = join(rootDir, "mock-cdn");
  2428. const cdnRoot = join(rootDir, "cdn");
  2429. await stageRemoteRuntimeRelease(mockCdnDir);
  2430. await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  2431. const cdnServer = await createStaticFileServer(cdnRoot);
  2432. try {
  2433. const backend = new FakeRemoteBackend(
  2434. Object.fromEntries(
  2435. Object.entries(LEGACY_REMOTE_TEST_AGENT_RUNTIME)
  2436. .filter(([, runtime]) => runtime.binaryKind === "node-script")
  2437. .map(([provider, runtime]) => [
  2438. `~/.zcode/server/agents/${runtime.bundledResourceDir}/.bundle-meta.json`,
  2439. JSON.stringify({
  2440. provider,
  2441. version: runtime.version,
  2442. platform: "linux-arm64",
  2443. }),
  2444. ]),
  2445. ),
  2446. {
  2447. serverVersion: "0.0.0-old",
  2448. commandPlans: [
  2449. {
  2450. matcher: /command -v curl/,
  2451. exitCode: 0,
  2452. stdoutText: "download=curl\ntar=tar\nsha256=sha256sum\n",
  2453. },
  2454. ],
  2455. },
  2456. );
  2457. const deployed = await deployServer(
  2458. backend,
  2459. { platform: "linux", arch: "arm64" },
  2460. {
  2461. force: true,
  2462. assetInstallMode: "remote-download",
  2463. remoteCdnBaseUrl: cdnServer.baseUrl,
  2464. },
  2465. );
  2466. expect(deployed).toBe(true);
  2467. expect(backend.uploads).toEqual([]);
  2468. expect(backend.commands.some((command) => command.includes("curl -fL"))).toBe(true);
  2469. expect(backend.commands.some((command) => command.includes("sha256sum"))).toBe(true);
  2470. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(1);
  2471. } finally {
  2472. await cdnServer.close();
  2473. }
  2474. });
  2475. it("生产态 manifest 初次 404 后同进程重试应重新探测 manifest", async () => {
  2476. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2477. tempDirs.push(rootDir);
  2478. const mockCdnDir = join(rootDir, "mock-cdn");
  2479. const cdnRoot = join(rootDir, "cdn");
  2480. const remoteCacheDir = join(rootDir, "remote-cache");
  2481. await stageRemoteRuntimeRelease(mockCdnDir);
  2482. const cdnServer = await createStaticFileServer(cdnRoot);
  2483. try {
  2484. await expect(
  2485. ensureRemoteReleaseDirFromCdn(
  2486. {
  2487. remoteCdnBaseUrl: cdnServer.baseUrl,
  2488. remoteCacheDir,
  2489. version: ZCODE_VERSION,
  2490. platformArch: "linux-arm64",
  2491. },
  2492. { log: () => {}, logWarn: () => {} },
  2493. ),
  2494. ).rejects.toThrow(/manifest not found/u);
  2495. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  2496. const serverBundle = manifest.components.find(
  2497. (component) => component.id === "server-bundle",
  2498. );
  2499. if (!serverBundle) {
  2500. throw new Error("missing server-bundle component in staged manifest");
  2501. }
  2502. const glm = manifest.components.find((component) => component.id === "glm");
  2503. if (!glm) {
  2504. throw new Error("missing glm component in staged manifest");
  2505. }
  2506. await expect(
  2507. ensureRemoteReleaseDirFromCdn(
  2508. {
  2509. remoteCdnBaseUrl: cdnServer.baseUrl,
  2510. remoteCacheDir,
  2511. version: ZCODE_VERSION,
  2512. platformArch: "linux-arm64",
  2513. },
  2514. { log: () => {}, logWarn: () => {} },
  2515. ),
  2516. ).resolves.toBe(
  2517. join(remoteCacheDir, "releases", ZCODE_VERSION, "linux-arm64", "glm-content", glm.sha256),
  2518. );
  2519. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(2);
  2520. expect(
  2521. cdnServer.getRequestCount(toVersionedArtifactRequestPath(serverBundle.artifactPath)),
  2522. ).toBe(0);
  2523. expect(
  2524. cdnServer.getRequestCount(toComponentArtifactRequestPath(serverBundle.artifactPath)),
  2525. ).toBe(1);
  2526. } finally {
  2527. await cdnServer.close();
  2528. }
  2529. });
  2530. it("生产态 remoteCdnBaseUrl 已固定版本时组件应从跨版本 components 根下载", async () => {
  2531. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2532. tempDirs.push(rootDir);
  2533. const mockCdnDir = join(rootDir, "mock-cdn");
  2534. const cdnRoot = join(rootDir, "cdn");
  2535. const remoteCacheDir = join(rootDir, "remote-cache");
  2536. await stageRemoteRuntimeRelease(mockCdnDir);
  2537. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  2538. const cdnServer = await createStaticFileServer(cdnRoot);
  2539. const serverBundle = manifest.components.find((component) => component.id === "server-bundle");
  2540. if (!serverBundle) {
  2541. throw new Error("missing server-bundle component in staged manifest");
  2542. }
  2543. const glm = manifest.components.find((component) => component.id === "glm");
  2544. if (!glm) {
  2545. throw new Error("missing glm component in staged manifest");
  2546. }
  2547. try {
  2548. await expect(
  2549. ensureRemoteReleaseDirFromCdn(
  2550. {
  2551. remoteCdnBaseUrl: `${cdnServer.baseUrl}/${ZCODE_VERSION}`,
  2552. remoteCacheDir,
  2553. version: ZCODE_VERSION,
  2554. platformArch: "linux-arm64",
  2555. },
  2556. { log: () => {}, logWarn: () => {} },
  2557. ),
  2558. ).resolves.toBe(
  2559. join(remoteCacheDir, "releases", ZCODE_VERSION, "linux-arm64", "glm-content", glm.sha256),
  2560. );
  2561. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(1);
  2562. expect(
  2563. cdnServer.getRequestCount(toVersionedArtifactRequestPath(serverBundle.artifactPath)),
  2564. ).toBe(0);
  2565. expect(
  2566. cdnServer.getRequestCount(toComponentArtifactRequestPath(serverBundle.artifactPath)),
  2567. ).toBe(1);
  2568. } finally {
  2569. await cdnServer.close();
  2570. }
  2571. });
  2572. it("生产态主 CDN 缺失组件时应回退到备选 CDN 下载组件", async () => {
  2573. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2574. tempDirs.push(rootDir);
  2575. const mockCdnDir = join(rootDir, "mock-cdn");
  2576. const primaryCdnRoot = join(rootDir, "primary-cdn");
  2577. const backupCdnRoot = join(rootDir, "backup-cdn");
  2578. const remoteCacheDir = join(rootDir, "remote-cache");
  2579. await stageRemoteRuntimeRelease(mockCdnDir);
  2580. const backupManifest = await stageRemoteComponentArtifacts(mockCdnDir, backupCdnRoot);
  2581. await mkdir(join(primaryCdnRoot, ZCODE_VERSION), { recursive: true });
  2582. await writeFile(
  2583. join(primaryCdnRoot, ZCODE_VERSION, "manifest-linux-arm64.json"),
  2584. JSON.stringify(backupManifest, null, 2),
  2585. "utf8",
  2586. );
  2587. const primaryCdnServer = await createStaticFileServer(primaryCdnRoot);
  2588. const backupCdnServer = await createStaticFileServer(backupCdnRoot);
  2589. const ripgrepBundle = backupManifest.components.find((component) => component.id === "ripgrep");
  2590. if (!ripgrepBundle) {
  2591. throw new Error("missing ripgrep component in staged manifest");
  2592. }
  2593. try {
  2594. const remoteFiles = {
  2595. "~/.zcode/server/agents/codex/.version": "0.0.0\n",
  2596. };
  2597. addMatchingServerBundleArtifactIdentity(remoteFiles, backupManifest, "linux-arm64");
  2598. const backend = new FakeRemoteBackend(remoteFiles);
  2599. const deployed = await deployServer(
  2600. backend,
  2601. { platform: "linux", arch: "arm64" },
  2602. {
  2603. force: false,
  2604. remoteCdnBaseUrls: [primaryCdnServer.baseUrl, backupCdnServer.baseUrl],
  2605. remoteCacheDir,
  2606. resourcePackages: {
  2607. selectedPackageIds: [retiredProxyRuntimeId],
  2608. },
  2609. },
  2610. );
  2611. expect(deployed).toBe(false);
  2612. expect(primaryCdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(
  2613. 1,
  2614. );
  2615. expect(backupCdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(
  2616. 0,
  2617. );
  2618. expect(
  2619. primaryCdnServer.getRequestCount(
  2620. toVersionedArtifactRequestPath(ripgrepBundle.artifactPath),
  2621. ),
  2622. ).toBe(1);
  2623. expect(
  2624. primaryCdnServer.getRequestCount(
  2625. toComponentArtifactRequestPath(ripgrepBundle.artifactPath),
  2626. ),
  2627. ).toBe(1);
  2628. expect(
  2629. backupCdnServer.getRequestCount(toVersionedArtifactRequestPath(ripgrepBundle.artifactPath)),
  2630. ).toBe(0);
  2631. expect(
  2632. backupCdnServer.getRequestCount(toComponentArtifactRequestPath(ripgrepBundle.artifactPath)),
  2633. ).toBe(1);
  2634. expect(
  2635. primaryCdnServer.getRequestCount(`/${ZCODE_VERSION}/remote-assets-linux-arm64.tar.gz`),
  2636. ).toBe(0);
  2637. expect(
  2638. backupCdnServer.getRequestCount(`/${ZCODE_VERSION}/remote-assets-linux-arm64.tar.gz`),
  2639. ).toBe(0);
  2640. } finally {
  2641. await primaryCdnServer.close();
  2642. await backupCdnServer.close();
  2643. }
  2644. });
  2645. it("manifest 命中备 CDN 时应优先从同一 CDN 下载 GLM 制品", async () => {
  2646. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2647. tempDirs.push(rootDir);
  2648. const mockCdnDir = join(rootDir, "mock-cdn");
  2649. const primaryCdnRoot = join(rootDir, "primary-cdn");
  2650. const backupCdnRoot = join(rootDir, "backup-cdn");
  2651. const remoteCacheDir = join(rootDir, "remote-cache");
  2652. await stageRemoteRuntimeRelease(mockCdnDir);
  2653. const backupManifest = await stageRemoteComponentArtifacts(mockCdnDir, backupCdnRoot);
  2654. const glm = backupManifest.components.find((component) => component.id === "glm");
  2655. if (!glm) {
  2656. throw new Error("missing glm component in staged manifest");
  2657. }
  2658. await mkdir(dirname(join(primaryCdnRoot, glm.artifactPath)), {
  2659. recursive: true,
  2660. });
  2661. await writeFile(
  2662. join(primaryCdnRoot, glm.artifactPath),
  2663. "stale primary CDN bytes with a checksum mismatch",
  2664. "utf8",
  2665. );
  2666. const primaryCdnServer = await createStaticFileServer(primaryCdnRoot);
  2667. const backupCdnServer = await createStaticFileServer(backupCdnRoot);
  2668. try {
  2669. const backend = new FakeRemoteBackend(createFullyDeployedRemoteFiles("linux-arm64"));
  2670. await deployServer(
  2671. backend,
  2672. { platform: "linux", arch: "arm64" },
  2673. {
  2674. remoteCdnBaseUrls: [primaryCdnServer.baseUrl, backupCdnServer.baseUrl],
  2675. remoteCacheDir,
  2676. },
  2677. );
  2678. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/agents/glm/zcode.cjs.new")).toBe(
  2679. true,
  2680. );
  2681. expect(
  2682. primaryCdnServer.getRequestCount(toComponentArtifactRequestPath(glm.artifactPath)),
  2683. ).toBe(0);
  2684. expect(
  2685. backupCdnServer.getRequestCount(toComponentArtifactRequestPath(glm.artifactPath)),
  2686. ).toBe(1);
  2687. } finally {
  2688. await primaryCdnServer.close();
  2689. await backupCdnServer.close();
  2690. }
  2691. });
  2692. it("生产态 manifest 缺失时不应再回退 legacy remote-assets 归档", async () => {
  2693. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2694. tempDirs.push(rootDir);
  2695. const mockCdnDir = join(rootDir, "mock-cdn");
  2696. const cdnRoot = join(rootDir, "cdn");
  2697. const remoteCacheDir = join(rootDir, "remote-cache");
  2698. await stageRemoteRuntimeRelease(mockCdnDir);
  2699. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot, {
  2700. writeManifest: false,
  2701. });
  2702. await stageRemoteAssetArchive(mockCdnDir, cdnRoot, {
  2703. useLegacyFileName: true,
  2704. });
  2705. const cdnServer = await createStaticFileServer(cdnRoot);
  2706. const serverBundle = manifest.components.find((component) => component.id === "server-bundle");
  2707. if (!serverBundle) {
  2708. throw new Error("missing server-bundle component in staged manifest");
  2709. }
  2710. try {
  2711. await expect(
  2712. deployServer(
  2713. new FakeRemoteBackend({
  2714. "~/.zcode/server/agents/codex/.version": "0.0.0\n",
  2715. }),
  2716. { platform: "linux", arch: "arm64" },
  2717. {
  2718. force: false,
  2719. remoteCdnBaseUrl: cdnServer.baseUrl,
  2720. remoteCacheDir,
  2721. },
  2722. ),
  2723. ).rejects.toThrow(/manifest not found/u);
  2724. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(1);
  2725. expect(
  2726. cdnServer.getRequestCount(toVersionedArtifactRequestPath(serverBundle.artifactPath)),
  2727. ).toBe(0);
  2728. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/remote-assets-linux-arm64.tar.gz`)).toBe(
  2729. 0,
  2730. );
  2731. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/remote-assets.tar.gz`)).toBe(0);
  2732. } finally {
  2733. await cdnServer.close();
  2734. }
  2735. });
  2736. it("生产态 cache 命中时不应重复下载组件产物", async () => {
  2737. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2738. tempDirs.push(rootDir);
  2739. const mockCdnDir = join(rootDir, "mock-cdn");
  2740. const cdnRoot = join(rootDir, "cdn");
  2741. const remoteCacheDir = join(rootDir, "remote-cache");
  2742. await stageRemoteRuntimeRelease(mockCdnDir);
  2743. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  2744. const cdnServer = await createStaticFileServer(cdnRoot);
  2745. const ripgrepBundle = manifest.components.find((component) => component.id === "ripgrep");
  2746. if (!ripgrepBundle) {
  2747. throw new Error("missing ripgrep component in staged manifest");
  2748. }
  2749. try {
  2750. await deployServer(
  2751. new FakeRemoteBackend({
  2752. "~/.zcode/server/agents/codex/.version": "0.0.0\n",
  2753. }),
  2754. { platform: "linux", arch: "arm64" },
  2755. {
  2756. force: false,
  2757. remoteCdnBaseUrl: cdnServer.baseUrl,
  2758. remoteCacheDir,
  2759. resourcePackages: {
  2760. selectedPackageIds: [`${retiredProtocolPrefix}-codex`],
  2761. },
  2762. },
  2763. );
  2764. await deployServer(
  2765. new FakeRemoteBackend({
  2766. "~/.zcode/server/agents/codex/.version": "0.0.0\n",
  2767. }),
  2768. { platform: "linux", arch: "arm64" },
  2769. {
  2770. force: false,
  2771. remoteCdnBaseUrl: cdnServer.baseUrl,
  2772. remoteCacheDir,
  2773. resourcePackages: {
  2774. selectedPackageIds: [`${retiredProtocolPrefix}-codex`],
  2775. },
  2776. },
  2777. );
  2778. expect(
  2779. cdnServer.getRequestCount(toVersionedArtifactRequestPath(ripgrepBundle.artifactPath)),
  2780. ).toBe(0);
  2781. expect(
  2782. cdnServer.getRequestCount(toComponentArtifactRequestPath(ripgrepBundle.artifactPath)),
  2783. ).toBe(1);
  2784. } finally {
  2785. await cdnServer.close();
  2786. }
  2787. });
  2788. it("生产态主 server 过期时应同时刷新 glm bundle", async () => {
  2789. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2790. tempDirs.push(rootDir);
  2791. const mockCdnDir = join(rootDir, "mock-cdn");
  2792. const cdnRoot = join(rootDir, "cdn");
  2793. const remoteCacheDir = join(rootDir, "remote-cache");
  2794. await stageRemoteRuntimeRelease(mockCdnDir);
  2795. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  2796. const cdnServer = await createStaticFileServer(cdnRoot);
  2797. try {
  2798. const backend = new FakeRemoteBackend(
  2799. {
  2800. ...createFullyDeployedRemoteFiles("linux-arm64"),
  2801. "~/.zcode/server/.asset-components/node-runtime.json": createRemoteAssetComponentMeta(
  2802. "node-runtime",
  2803. findManifestComponent(manifest, "node-runtime").version,
  2804. "linux-arm64",
  2805. ),
  2806. "~/.zcode/server/.asset-components/node-pty.json": createRemoteAssetComponentMeta(
  2807. "node-pty",
  2808. findManifestComponent(manifest, "node-pty").version,
  2809. "linux-arm64",
  2810. ),
  2811. },
  2812. {
  2813. serverVersion: "1.9.0",
  2814. },
  2815. );
  2816. const deployed = await deployServer(
  2817. backend,
  2818. { platform: "linux", arch: "arm64" },
  2819. {
  2820. force: false,
  2821. remoteCdnBaseUrl: cdnServer.baseUrl,
  2822. remoteCacheDir,
  2823. },
  2824. );
  2825. expect(deployed).toBe(true);
  2826. expect(backend.uploads).toHaveLength(3);
  2827. expect(backend.uploads.map((upload) => upload.remotePath)).toEqual(
  2828. expect.arrayContaining([
  2829. expect.stringMatching(/^~\/.zcode\/server\/zcode-server\.cjs\.new-[\w-]+$/u),
  2830. expect.stringMatching(/^~\/.zcode\/server\/agents\/glm\/zcode\.cjs\.new-[\w-]+$/u),
  2831. expect.stringMatching(/^~\/.zcode\/server\/agents\/glm\/packages\.tar\.gz-[\w-]+$/u),
  2832. ]),
  2833. );
  2834. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(1);
  2835. for (const componentId of ["server-bundle"]) {
  2836. expect(
  2837. cdnServer.getRequestCount(
  2838. toVersionedArtifactRequestPath(
  2839. findManifestComponent(manifest, componentId).artifactPath,
  2840. ),
  2841. ),
  2842. ).toBe(0);
  2843. expect(
  2844. cdnServer.getRequestCount(
  2845. toComponentArtifactRequestPath(
  2846. findManifestComponent(manifest, componentId).artifactPath,
  2847. ),
  2848. ),
  2849. ).toBe(1);
  2850. }
  2851. for (const componentId of [
  2852. "node-runtime",
  2853. "node-pty",
  2854. `${retiredProtocolPrefix}-codex`,
  2855. "glm",
  2856. "ripgrep",
  2857. ]) {
  2858. expect(
  2859. cdnServer.getRequestCount(
  2860. toVersionedArtifactRequestPath(
  2861. findManifestComponent(manifest, componentId).artifactPath,
  2862. ),
  2863. ),
  2864. ).toBe(0);
  2865. }
  2866. } finally {
  2867. await cdnServer.close();
  2868. }
  2869. });
  2870. it("local-download-upload 下 App 版本变化时即使 server-bundle 与 GLM SHA cache 命中也应重新下载上传", async () => {
  2871. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2872. tempDirs.push(rootDir);
  2873. const mockCdnDir = join(rootDir, "mock-cdn");
  2874. const cdnRoot = join(rootDir, "cdn");
  2875. const remoteCacheDir = join(rootDir, "remote-cache");
  2876. await stageRemoteRuntimeRelease(mockCdnDir);
  2877. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  2878. const cdnServer = await createStaticFileServer(cdnRoot);
  2879. const serverBundle = findManifestComponent(manifest, "server-bundle");
  2880. const glm = findManifestComponent(manifest, "glm");
  2881. try {
  2882. const warmCacheBackend = new FakeRemoteBackend(createFullyDeployedRemoteFiles("linux-arm64"));
  2883. await deployServer(
  2884. warmCacheBackend,
  2885. { platform: "linux", arch: "arm64" },
  2886. {
  2887. force: false,
  2888. remoteCdnBaseUrl: cdnServer.baseUrl,
  2889. remoteCacheDir,
  2890. },
  2891. );
  2892. expect(
  2893. cdnServer.getRequestCount(toComponentArtifactRequestPath(serverBundle.artifactPath)),
  2894. ).toBe(1);
  2895. expect(cdnServer.getRequestCount(toComponentArtifactRequestPath(glm.artifactPath))).toBe(1);
  2896. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  2897. addMatchingGlmAndServerArtifactIdentities(remoteFiles, manifest, "linux-arm64");
  2898. remoteFiles["~/.zcode/server/.asset-components/node-runtime.json"] =
  2899. createRemoteAssetComponentMeta(
  2900. "node-runtime",
  2901. findManifestComponent(manifest, "node-runtime").version,
  2902. "linux-arm64",
  2903. );
  2904. remoteFiles["~/.zcode/server/.asset-components/node-pty.json"] =
  2905. createRemoteAssetComponentMeta(
  2906. "node-pty",
  2907. findManifestComponent(manifest, "node-pty").version,
  2908. "linux-arm64",
  2909. );
  2910. const backend = new FakeRemoteBackend(remoteFiles, {
  2911. serverVersion: "3.4.0-old-app",
  2912. });
  2913. const deployed = await deployServer(
  2914. backend,
  2915. { platform: "linux", arch: "arm64" },
  2916. {
  2917. force: false,
  2918. remoteCdnBaseUrl: cdnServer.baseUrl,
  2919. remoteCacheDir,
  2920. },
  2921. );
  2922. expect(deployed).toBe(true);
  2923. expect(
  2924. cdnServer.getRequestCount(toComponentArtifactRequestPath(serverBundle.artifactPath)),
  2925. ).toBe(2);
  2926. expect(cdnServer.getRequestCount(toComponentArtifactRequestPath(glm.artifactPath))).toBe(2);
  2927. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/agents/glm/zcode.cjs.new")).toBe(
  2928. true,
  2929. );
  2930. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/agents/glm/packages.tar.gz")).toBe(
  2931. true,
  2932. );
  2933. } finally {
  2934. await cdnServer.close();
  2935. }
  2936. });
  2937. it("App 版本变化后 GLM 部署失败时下次连接应继续强制刷新 cache", async () => {
  2938. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  2939. tempDirs.push(rootDir);
  2940. const mockCdnDir = join(rootDir, "mock-cdn");
  2941. const cdnRoot = join(rootDir, "cdn");
  2942. const remoteCacheDir = join(rootDir, "remote-cache");
  2943. await stageRemoteRuntimeRelease(mockCdnDir);
  2944. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  2945. const cdnServer = await createStaticFileServer(cdnRoot);
  2946. const glm = findManifestComponent(manifest, "glm");
  2947. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  2948. addMatchingGlmAndServerArtifactIdentities(remoteFiles, manifest, "linux-arm64");
  2949. remoteFiles["~/.zcode/server/.asset-components/node-runtime.json"] =
  2950. createRemoteAssetComponentMeta(
  2951. "node-runtime",
  2952. findManifestComponent(manifest, "node-runtime").version,
  2953. "linux-arm64",
  2954. );
  2955. remoteFiles["~/.zcode/server/.asset-components/node-pty.json"] = createRemoteAssetComponentMeta(
  2956. "node-pty",
  2957. findManifestComponent(manifest, "node-pty").version,
  2958. "linux-arm64",
  2959. );
  2960. let remoteServerVersion = "3.4.0-old-app";
  2961. let backend: FailFirstGlmUploadRemoteBackend;
  2962. backend = new FailFirstGlmUploadRemoteBackend(remoteFiles, {
  2963. serverVersion: () => remoteServerVersion,
  2964. commandPlans: [
  2965. {
  2966. matcher: /command mv -f .*zcode-server\.cjs\.new.*zcode-server\.cjs/u,
  2967. exitCode: 0,
  2968. onExec: () => {
  2969. remoteServerVersion = ZCODE_VERSION;
  2970. },
  2971. },
  2972. {
  2973. matcher: /pendingRefreshAppVersion/u,
  2974. exitCode: 0,
  2975. onExec: () => {
  2976. backend.remoteFiles.set(
  2977. "~/.zcode/server/.asset-components/glm.json",
  2978. JSON.stringify({
  2979. id: "glm",
  2980. platformArch: "linux-arm64",
  2981. pendingRefreshAppVersion: ZCODE_VERSION,
  2982. }),
  2983. );
  2984. },
  2985. },
  2986. ],
  2987. });
  2988. try {
  2989. await expect(
  2990. deployServer(
  2991. backend,
  2992. { platform: "linux", arch: "arm64" },
  2993. {
  2994. force: false,
  2995. remoteCdnBaseUrl: cdnServer.baseUrl,
  2996. remoteCacheDir,
  2997. },
  2998. ),
  2999. ).rejects.toThrow("mock glm upload failed");
  3000. expect(remoteServerVersion).toBe(ZCODE_VERSION);
  3001. expect(backend.remoteFiles.get("~/.zcode/server/.asset-components/glm.json")).toContain(
  3002. "pendingRefreshAppVersion",
  3003. );
  3004. expect(cdnServer.getRequestCount(toComponentArtifactRequestPath(glm.artifactPath))).toBe(1);
  3005. const firstAttemptCommands = backend.commands.slice();
  3006. const refreshPendingCommandIndex = firstAttemptCommands.findIndex((command) =>
  3007. command.includes("pendingRefreshAppVersion"),
  3008. );
  3009. const serverReplaceCommandIndex = firstAttemptCommands.findIndex(
  3010. (command) => command.includes("command mv -f ") && command.includes("zcode-server.cjs.new"),
  3011. );
  3012. expect(refreshPendingCommandIndex).toBeGreaterThanOrEqual(0);
  3013. expect(serverReplaceCommandIndex).toBeGreaterThan(refreshPendingCommandIndex);
  3014. expect(
  3015. firstAttemptCommands.some(
  3016. (command) =>
  3017. !command.includes("pendingRefreshAppVersion") &&
  3018. command.includes(".asset-components/glm.json"),
  3019. ),
  3020. ).toBe(false);
  3021. const deployed = await deployServer(
  3022. backend,
  3023. { platform: "linux", arch: "arm64" },
  3024. {
  3025. force: false,
  3026. remoteCdnBaseUrl: cdnServer.baseUrl,
  3027. remoteCacheDir,
  3028. },
  3029. );
  3030. expect(deployed).toBe(false);
  3031. expect(cdnServer.getRequestCount(toComponentArtifactRequestPath(glm.artifactPath))).toBe(2);
  3032. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/agents/glm/zcode.cjs.new")).toBe(
  3033. true,
  3034. );
  3035. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/agents/glm/packages.tar.gz")).toBe(
  3036. true,
  3037. );
  3038. expect(
  3039. backend.commands
  3040. .slice(firstAttemptCommands.length)
  3041. .some(
  3042. (command) =>
  3043. !command.includes("pendingRefreshAppVersion") &&
  3044. command.includes(".asset-components/glm.json"),
  3045. ),
  3046. ).toBe(true);
  3047. } finally {
  3048. await cdnServer.close();
  3049. }
  3050. });
  3051. it("remote-download 下 App 版本变化时即使 server-bundle 与 GLM SHA 匹配也应重新下载部署", async () => {
  3052. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3053. tempDirs.push(rootDir);
  3054. const mockCdnDir = join(rootDir, "mock-cdn");
  3055. const cdnRoot = join(rootDir, "cdn");
  3056. await stageRemoteRuntimeRelease(mockCdnDir);
  3057. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  3058. const cdnServer = await createStaticFileServer(cdnRoot);
  3059. const serverBundle = findManifestComponent(manifest, "server-bundle");
  3060. const glm = findManifestComponent(manifest, "glm");
  3061. const serverBundleCacheDir = `~/.zcode/server/asset-cache/components/linux-arm64/server-bundle/${serverBundle.sha256}`;
  3062. const glmCacheDir = `~/.zcode/server/asset-cache/components/linux-arm64/glm/${glm.sha256}`;
  3063. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  3064. addMatchingGlmAndServerArtifactIdentities(remoteFiles, manifest, "linux-arm64");
  3065. remoteFiles[`${serverBundleCacheDir}/.ready`] = "ready";
  3066. remoteFiles[`${glmCacheDir}/.ready`] = "ready";
  3067. remoteFiles["~/.zcode/server/.asset-components/node-runtime.json"] =
  3068. createRemoteAssetComponentMeta(
  3069. "node-runtime",
  3070. findManifestComponent(manifest, "node-runtime").version,
  3071. "linux-arm64",
  3072. );
  3073. remoteFiles["~/.zcode/server/.asset-components/node-pty.json"] = createRemoteAssetComponentMeta(
  3074. "node-pty",
  3075. findManifestComponent(manifest, "node-pty").version,
  3076. "linux-arm64",
  3077. );
  3078. const backend = new FakeRemoteBackend(remoteFiles, {
  3079. serverVersion: "3.4.0-old-app",
  3080. commandPlans: [
  3081. {
  3082. matcher: /command -v curl/u,
  3083. exitCode: 0,
  3084. stdoutText: "download=curl\ntar=tar\nsha256=sha256sum\n",
  3085. },
  3086. ],
  3087. });
  3088. try {
  3089. const deployed = await deployServer(
  3090. backend,
  3091. { platform: "linux", arch: "arm64" },
  3092. {
  3093. force: false,
  3094. assetInstallMode: "remote-download",
  3095. remoteCdnBaseUrl: cdnServer.baseUrl,
  3096. },
  3097. );
  3098. expect(deployed).toBe(true);
  3099. expect(backend.uploads).toEqual([]);
  3100. expect(
  3101. backend.commands.filter((command) => command.includes(serverBundle.artifactPath)),
  3102. ).toHaveLength(1);
  3103. expect(
  3104. backend.commands.some((command) =>
  3105. command.includes(
  3106. `rm -rf "$HOME"'/.zcode/server/asset-cache/components/linux-arm64/server-bundle/${serverBundle.sha256}'`,
  3107. ),
  3108. ),
  3109. ).toBe(true);
  3110. expect(backend.commands.some((command) => command.includes(glm.artifactPath))).toBe(true);
  3111. expect(backend.commands.filter((command) => command.includes(glm.artifactPath))).toHaveLength(
  3112. 1,
  3113. );
  3114. expect(
  3115. backend.commands.some((command) =>
  3116. command.includes(
  3117. `rm -rf "$HOME"'/.zcode/server/asset-cache/components/linux-arm64/glm/${glm.sha256}'`,
  3118. ),
  3119. ),
  3120. ).toBe(true);
  3121. expect(
  3122. backend.commands.some((command) => command.includes(".asset-components/glm.json")),
  3123. ).toBe(true);
  3124. } finally {
  3125. await cdnServer.close();
  3126. }
  3127. });
  3128. it("remote-download 下 App 版本变化后中间部署失败时应在重试中继续强刷 GLM cache", async () => {
  3129. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3130. tempDirs.push(rootDir);
  3131. const mockCdnDir = join(rootDir, "mock-cdn");
  3132. const cdnRoot = join(rootDir, "cdn");
  3133. await stageRemoteRuntimeRelease(mockCdnDir);
  3134. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  3135. const cdnServer = await createStaticFileServer(cdnRoot);
  3136. const serverBundle = findManifestComponent(manifest, "server-bundle");
  3137. const glm = findManifestComponent(manifest, "glm");
  3138. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  3139. addMatchingGlmAndServerArtifactIdentities(remoteFiles, manifest, "linux-arm64");
  3140. remoteFiles[
  3141. `~/.zcode/server/asset-cache/components/linux-arm64/server-bundle/${serverBundle.sha256}/.ready`
  3142. ] = "ready";
  3143. remoteFiles[`~/.zcode/server/asset-cache/components/linux-arm64/glm/${glm.sha256}/.ready`] =
  3144. "ready";
  3145. remoteFiles["~/.zcode/server/.asset-components/node-runtime.json"] =
  3146. createRemoteAssetComponentMeta(
  3147. "node-runtime",
  3148. findManifestComponent(manifest, "node-runtime").version,
  3149. "linux-arm64",
  3150. );
  3151. let remoteServerVersion = "3.4.0-old-app";
  3152. let backend: FailFirstNodePtyInstallRemoteBackend;
  3153. backend = new FailFirstNodePtyInstallRemoteBackend(remoteFiles, {
  3154. serverVersion: () => remoteServerVersion,
  3155. commandPlans: [
  3156. {
  3157. matcher: /command -v curl/u,
  3158. exitCode: 0,
  3159. stdoutText: "download=curl\ntar=tar\nsha256=sha256sum\n",
  3160. },
  3161. {
  3162. matcher: /command mv -f .*zcode-server\.cjs\.new.*zcode-server\.cjs/u,
  3163. exitCode: 0,
  3164. onExec: () => {
  3165. remoteServerVersion = ZCODE_VERSION;
  3166. },
  3167. },
  3168. {
  3169. matcher: /pendingRefreshAppVersion/u,
  3170. exitCode: 0,
  3171. onExec: () => {
  3172. backend.remoteFiles.set(
  3173. "~/.zcode/server/.asset-components/glm.json",
  3174. JSON.stringify({
  3175. id: "glm",
  3176. platformArch: "linux-arm64",
  3177. pendingRefreshAppVersion: ZCODE_VERSION,
  3178. }),
  3179. );
  3180. },
  3181. },
  3182. ],
  3183. });
  3184. try {
  3185. await expect(
  3186. deployServer(
  3187. backend,
  3188. { platform: "linux", arch: "arm64" },
  3189. {
  3190. assetInstallMode: "remote-download",
  3191. remoteCdnBaseUrl: cdnServer.baseUrl,
  3192. },
  3193. ),
  3194. ).rejects.toThrow("mock node-pty install failed");
  3195. expect(remoteServerVersion).toBe(ZCODE_VERSION);
  3196. expect(backend.commands.some((command) => command.includes(glm.artifactPath))).toBe(false);
  3197. const deployed = await deployServer(
  3198. backend,
  3199. { platform: "linux", arch: "arm64" },
  3200. {
  3201. assetInstallMode: "remote-download",
  3202. remoteCdnBaseUrl: cdnServer.baseUrl,
  3203. },
  3204. );
  3205. expect(deployed).toBe(false);
  3206. expect(backend.commands.filter((command) => command.includes(glm.artifactPath))).toHaveLength(
  3207. 1,
  3208. );
  3209. expect(
  3210. backend.commands.some((command) =>
  3211. command.includes(
  3212. `rm -rf "$HOME"'/.zcode/server/asset-cache/components/linux-arm64/glm/${glm.sha256}'`,
  3213. ),
  3214. ),
  3215. ).toBe(true);
  3216. } finally {
  3217. await cdnServer.close();
  3218. }
  3219. });
  3220. it("开发态 mock-cdn 有匹配组件版本时主 server 过期不应重传 node runtime", async () => {
  3221. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3222. tempDirs.push(rootDir);
  3223. const mockCdnDir = join(rootDir, "mock-cdn");
  3224. await stageRemoteRuntimeRelease(mockCdnDir);
  3225. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, join(mockCdnDir, "releases"));
  3226. const nodeRuntime = manifest.components.find((component) => component.id === "node-runtime");
  3227. if (!nodeRuntime) {
  3228. throw new Error("missing node-runtime component in staged manifest");
  3229. }
  3230. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
  3231. try {
  3232. const backend = new FakeRemoteBackend(
  3233. {
  3234. ...createFullyDeployedRemoteFiles("linux-arm64"),
  3235. "~/.zcode/server/.asset-components/node-runtime.json": createRemoteAssetComponentMeta(
  3236. "node-runtime",
  3237. nodeRuntime.version,
  3238. "linux-arm64",
  3239. ),
  3240. },
  3241. {
  3242. serverVersion: "1.9.0",
  3243. },
  3244. );
  3245. await deployServer(
  3246. backend,
  3247. { platform: "linux", arch: "arm64" },
  3248. {
  3249. force: false,
  3250. mockCdnDir,
  3251. },
  3252. );
  3253. expect(backend.uploads.map((upload) => upload.remotePath)).not.toContain(
  3254. "~/.zcode/server/node.new",
  3255. );
  3256. const warnLines = warnSpy.mock.calls.map((args) => args.map((arg) => String(arg)).join(" "));
  3257. expect(
  3258. warnLines.some(
  3259. (line) =>
  3260. line.includes("component=node-runtime") &&
  3261. line.includes("component version unavailable"),
  3262. ),
  3263. ).toBe(false);
  3264. } finally {
  3265. warnSpy.mockRestore();
  3266. }
  3267. });
  3268. it("生产态主 server 过期但 node 版本不匹配时应记录原因并重传 node", async () => {
  3269. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3270. tempDirs.push(rootDir);
  3271. const mockCdnDir = join(rootDir, "mock-cdn");
  3272. const cdnRoot = join(rootDir, "cdn");
  3273. const remoteCacheDir = join(rootDir, "remote-cache");
  3274. await stageRemoteRuntimeRelease(mockCdnDir);
  3275. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  3276. const cdnServer = await createStaticFileServer(cdnRoot);
  3277. const nodeRuntime = manifest.components.find((component) => component.id === "node-runtime");
  3278. if (!nodeRuntime) {
  3279. throw new Error("missing node-runtime component in staged manifest");
  3280. }
  3281. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
  3282. try {
  3283. const backend = new FakeRemoteBackend(
  3284. {
  3285. ...createFullyDeployedRemoteFiles("linux-arm64"),
  3286. "~/.zcode/server/.asset-components/node-runtime.json": createRemoteAssetComponentMeta(
  3287. "node-runtime",
  3288. "old-node-version",
  3289. "linux-arm64",
  3290. ),
  3291. "~/.zcode/server/.asset-components/node-pty.json": createRemoteAssetComponentMeta(
  3292. "node-pty",
  3293. "1.0.0-node-pty",
  3294. "linux-arm64",
  3295. ),
  3296. },
  3297. {
  3298. serverVersion: "1.9.0",
  3299. },
  3300. );
  3301. await deployServer(
  3302. backend,
  3303. { platform: "linux", arch: "arm64" },
  3304. {
  3305. force: false,
  3306. remoteCdnBaseUrl: cdnServer.baseUrl,
  3307. remoteCacheDir,
  3308. },
  3309. );
  3310. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/node.new")).toBe(true);
  3311. expect(
  3312. cdnServer.getRequestCount(toVersionedArtifactRequestPath(nodeRuntime.artifactPath)),
  3313. ).toBe(0);
  3314. expect(
  3315. cdnServer.getRequestCount(toComponentArtifactRequestPath(nodeRuntime.artifactPath)),
  3316. ).toBe(1);
  3317. const warnLines = warnSpy.mock.calls.map((args) => args.map((arg) => String(arg)).join(" "));
  3318. expect(
  3319. warnLines.some(
  3320. (line) =>
  3321. line.includes("[remote-assets] upload required") &&
  3322. line.includes("component=node-runtime") &&
  3323. line.includes("remote version mismatch") &&
  3324. line.includes("old-node-version"),
  3325. ),
  3326. ).toBe(true);
  3327. } finally {
  3328. warnSpy.mockRestore();
  3329. await cdnServer.close();
  3330. }
  3331. });
  3332. it("版本匹配但 runtime tool binary 缺失时应补传并记录原因", async () => {
  3333. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3334. tempDirs.push(rootDir);
  3335. const mockCdnDir = join(rootDir, "mock-cdn");
  3336. await stageRemoteRuntimeRelease(mockCdnDir);
  3337. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  3338. delete remoteFiles["~/.zcode/server/tools/ripgrep/rg"];
  3339. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
  3340. try {
  3341. const backend = new FakeRemoteBackend(remoteFiles);
  3342. await deployServer(
  3343. backend,
  3344. { platform: "linux", arch: "arm64" },
  3345. {
  3346. force: false,
  3347. mockCdnDir,
  3348. },
  3349. );
  3350. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/tools/ripgrep/rg.new")).toBe(true);
  3351. const warnLines = warnSpy.mock.calls.map((args) => args.map((arg) => String(arg)).join(" "));
  3352. expect(
  3353. warnLines.some(
  3354. (line) =>
  3355. line.includes("[remote-assets] upload required") &&
  3356. line.includes("component=ripgrep") &&
  3357. line.includes("remote binary missing"),
  3358. ),
  3359. ).toBe(true);
  3360. } finally {
  3361. warnSpy.mockRestore();
  3362. }
  3363. });
  3364. it("主 server 版本匹配但 glm wrapper 缺失时应补传", async () => {
  3365. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3366. tempDirs.push(rootDir);
  3367. const mockCdnDir = join(rootDir, "mock-cdn");
  3368. await stageRemoteRuntimeRelease(mockCdnDir);
  3369. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, join(mockCdnDir, "releases"));
  3370. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  3371. addMatchingGlmAndServerArtifactIdentities(remoteFiles, manifest, "linux-arm64");
  3372. delete remoteFiles["~/.zcode/server/agents/glm/zcode-agent"];
  3373. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
  3374. try {
  3375. const backend = new FakeRemoteBackend(remoteFiles);
  3376. await deployServer(
  3377. backend,
  3378. { platform: "linux", arch: "arm64" },
  3379. {
  3380. force: false,
  3381. mockCdnDir,
  3382. },
  3383. );
  3384. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/agents/glm/zcode.cjs.new")).toBe(
  3385. true,
  3386. );
  3387. const warnLines = warnSpy.mock.calls.map((args) => args.map((arg) => String(arg)).join(" "));
  3388. expect(
  3389. warnLines.some(
  3390. (line) =>
  3391. line.includes("[remote-assets] upload required") &&
  3392. line.includes("component=glm") &&
  3393. line.includes("remote wrapper missing"),
  3394. ),
  3395. ).toBe(true);
  3396. } finally {
  3397. warnSpy.mockRestore();
  3398. }
  3399. });
  3400. it("主 server 版本匹配且 glm SHA 相同但版本不同时不应补传", async () => {
  3401. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3402. tempDirs.push(rootDir);
  3403. const mockCdnDir = join(rootDir, "mock-cdn");
  3404. await stageRemoteRuntimeRelease(mockCdnDir);
  3405. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, join(mockCdnDir, "releases"));
  3406. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  3407. addMatchingGlmAndServerArtifactIdentities(
  3408. remoteFiles,
  3409. manifest,
  3410. "linux-arm64",
  3411. "0.0.1-old-version",
  3412. );
  3413. const backend = new FakeRemoteBackend(remoteFiles);
  3414. await deployServer(
  3415. backend,
  3416. { platform: "linux", arch: "arm64" },
  3417. {
  3418. force: false,
  3419. mockCdnDir,
  3420. },
  3421. );
  3422. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/agents/glm/zcode.cjs.new")).toBe(
  3423. false,
  3424. );
  3425. expect(backend.commands.some((command) => command.includes(".asset-components/glm.json"))).toBe(
  3426. false,
  3427. );
  3428. expect(
  3429. backend.uploads.some(
  3430. (upload) => upload.remotePath === "~/.zcode/server/agents/opencode/opencode.new",
  3431. ),
  3432. ).toBe(false);
  3433. });
  3434. it("生产态远端 GLM SHA 匹配时只读取 manifest 而不下载制品", async () => {
  3435. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3436. tempDirs.push(rootDir);
  3437. const mockCdnDir = join(rootDir, "mock-cdn");
  3438. const cdnRoot = join(rootDir, "cdn");
  3439. const remoteCacheDir = join(rootDir, "remote-cache");
  3440. await stageRemoteRuntimeRelease(mockCdnDir);
  3441. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  3442. const cdnServer = await createStaticFileServer(cdnRoot);
  3443. try {
  3444. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  3445. addMatchingGlmAndServerArtifactIdentities(remoteFiles, manifest, "linux-arm64");
  3446. const backend = new FakeRemoteBackend(remoteFiles);
  3447. const deployed = await deployServer(
  3448. backend,
  3449. { platform: "linux", arch: "arm64" },
  3450. {
  3451. force: false,
  3452. remoteCdnBaseUrl: cdnServer.baseUrl,
  3453. remoteCacheDir,
  3454. },
  3455. );
  3456. expect(deployed).toBe(false);
  3457. expect(backend.uploads).toEqual([]);
  3458. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(1);
  3459. const glm = manifest.components.find((component) => component.id === "glm");
  3460. if (!glm) {
  3461. throw new Error("missing glm component in staged manifest");
  3462. }
  3463. expect(cdnServer.getRequestCount(toComponentArtifactRequestPath(glm.artifactPath))).toBe(0);
  3464. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/remote-assets-linux-arm64.tar.gz`)).toBe(
  3465. 0,
  3466. );
  3467. } finally {
  3468. await cdnServer.close();
  3469. }
  3470. });
  3471. it("远端已部署时 manifest 响应超时应有界失败且允许下一次连接重试", async () => {
  3472. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3473. tempDirs.push(rootDir);
  3474. const cdnRoot = join(rootDir, "cdn");
  3475. const remoteCacheDir = join(rootDir, "remote-cache");
  3476. const manifestPath = `/${ZCODE_VERSION}/manifest-linux-arm64.json`;
  3477. const cdnServer = await createStaticFileServer(cdnRoot, {
  3478. stalledPaths: [manifestPath],
  3479. });
  3480. const backend = new FakeRemoteBackend(createFullyDeployedRemoteFiles("linux-arm64"));
  3481. const logWarn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  3482. try {
  3483. let previousRequestCount = 0;
  3484. for (let attempt = 0; attempt < 2; attempt += 1) {
  3485. const startedAt = Date.now();
  3486. await expect(
  3487. deployServer(
  3488. backend,
  3489. { platform: "linux", arch: "arm64" },
  3490. {
  3491. remoteCdnBaseUrl: cdnServer.baseUrl,
  3492. remoteCacheDir,
  3493. manifestRequestTimeoutMs: 25,
  3494. },
  3495. ),
  3496. ).rejects.toThrow(/failed to fetch manifest-linux-arm64\.json/u);
  3497. expect(Date.now() - startedAt).toBeLessThan(1_000);
  3498. const requestCount = cdnServer.getRequestCount(manifestPath);
  3499. expect(requestCount).toBeGreaterThan(previousRequestCount);
  3500. previousRequestCount = requestCount;
  3501. }
  3502. expect(
  3503. logWarn.mock.calls.some((args) => args.some((arg) => String(arg).includes("TimeoutError"))),
  3504. ).toBe(true);
  3505. expect(backend.uploads).toEqual([]);
  3506. } finally {
  3507. logWarn.mockRestore();
  3508. await cdnServer.close();
  3509. }
  3510. });
  3511. it("首次部署的 manifest 超时不应在锁内降级重拉", async () => {
  3512. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3513. tempDirs.push(rootDir);
  3514. const cdnRoot = join(rootDir, "cdn");
  3515. const remoteCacheDir = join(rootDir, "remote-cache");
  3516. const manifestPath = `/${ZCODE_VERSION}/manifest-linux-arm64.json`;
  3517. const cdnServer = await createStaticFileServer(cdnRoot, {
  3518. stalledPaths: [manifestPath],
  3519. });
  3520. const backend = new FakeRemoteBackend({});
  3521. try {
  3522. const startedAt = Date.now();
  3523. await expect(
  3524. deployServer(
  3525. backend,
  3526. { platform: "linux", arch: "arm64" },
  3527. {
  3528. remoteCdnBaseUrl: cdnServer.baseUrl,
  3529. remoteCacheDir,
  3530. manifestRequestTimeoutMs: 25,
  3531. },
  3532. ),
  3533. ).rejects.toThrow(/failed to fetch manifest-linux-arm64\.json/u);
  3534. expect(Date.now() - startedAt).toBeLessThan(1_000);
  3535. // Bugfix:pinned manifest 失败就是本次 transaction 的失败,
  3536. // 不能再走 version resolver 发起第二个默认 10s 请求。
  3537. expect(cdnServer.getRequestCount(manifestPath)).toBe(1);
  3538. } finally {
  3539. await cdnServer.close();
  3540. }
  3541. });
  3542. it("component version resolver 应透传 manifest request deadline", async () => {
  3543. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3544. tempDirs.push(rootDir);
  3545. const cdnRoot = join(rootDir, "cdn");
  3546. const remoteCacheDir = join(rootDir, "remote-cache");
  3547. const manifestPath = `/${ZCODE_VERSION}/manifest-linux-arm64.json`;
  3548. const cdnServer = await createStaticFileServer(cdnRoot, {
  3549. stalledPaths: [manifestPath],
  3550. });
  3551. try {
  3552. const resolveVersion = createRemoteComponentVersionResolver(
  3553. {
  3554. remoteCdnBaseUrl: cdnServer.baseUrl,
  3555. remoteCacheDir,
  3556. manifestRequestTimeoutMs: 25,
  3557. },
  3558. { platform: "linux", arch: "arm64" },
  3559. { log: () => {}, logWarn: () => {} },
  3560. );
  3561. const startedAt = Date.now();
  3562. await expect(resolveVersion("node-runtime")).rejects.toThrow(
  3563. /failed to fetch manifest-linux-arm64\.json/u,
  3564. );
  3565. expect(Date.now() - startedAt).toBeLessThan(1_000);
  3566. expect(cdnServer.getRequestCount(manifestPath)).toBe(1);
  3567. } finally {
  3568. await cdnServer.close();
  3569. }
  3570. });
  3571. it("remote-download manifest 超时应保留 CDN 候选诊断", async () => {
  3572. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3573. tempDirs.push(rootDir);
  3574. const cdnRoot = join(rootDir, "cdn");
  3575. const manifestPath = `/${ZCODE_VERSION}/manifest-linux-arm64.json`;
  3576. const cdnServer = await createStaticFileServer(cdnRoot, {
  3577. stalledPaths: [manifestPath],
  3578. });
  3579. try {
  3580. await expect(
  3581. fetchRemoteDownloadManifest(
  3582. {
  3583. version: ZCODE_VERSION,
  3584. platformArch: "linux-arm64",
  3585. remoteCdnBaseUrl: cdnServer.baseUrl,
  3586. manifestRequestTimeoutMs: 25,
  3587. },
  3588. { log: () => {}, logWarn: () => {} },
  3589. ),
  3590. ).rejects.toThrow(/failed to fetch manifest.*TimeoutError/u);
  3591. expect(cdnServer.getRequestCount(manifestPath)).toBe(1);
  3592. } finally {
  3593. await cdnServer.close();
  3594. }
  3595. });
  3596. it("同一进程内 GLM 版本不变但 manifest SHA 更新时应重新部署", async () => {
  3597. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3598. tempDirs.push(rootDir);
  3599. const mockCdnDir = join(rootDir, "mock-cdn");
  3600. const cdnRoot = join(rootDir, "cdn");
  3601. const remoteCacheDir = join(rootDir, "remote-cache");
  3602. await stageRemoteRuntimeRelease(mockCdnDir);
  3603. const initialManifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  3604. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  3605. addMatchingGlmAndServerArtifactIdentities(remoteFiles, initialManifest, "linux-arm64");
  3606. const backend = new FakeRemoteBackend(remoteFiles);
  3607. const cdnServer = await createStaticFileServer(cdnRoot);
  3608. try {
  3609. await deployServer(
  3610. backend,
  3611. { platform: "linux", arch: "arm64" },
  3612. {
  3613. force: false,
  3614. remoteCdnBaseUrl: cdnServer.baseUrl,
  3615. remoteCacheDir,
  3616. },
  3617. );
  3618. expect(backend.uploads).toEqual([]);
  3619. await writeFile(
  3620. join(mockCdnDir, "releases", ZCODE_VERSION, "glm", "linux-arm64", "zcode.cjs"),
  3621. "glm bundle republished with the same semantic version",
  3622. "utf8",
  3623. );
  3624. const updatedManifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  3625. const initialGlm = initialManifest.components.find((component) => component.id === "glm");
  3626. const updatedGlm = updatedManifest.components.find((component) => component.id === "glm");
  3627. expect(updatedGlm?.version).toBe(initialGlm?.version);
  3628. expect(updatedGlm?.sha256).not.toBe(initialGlm?.sha256);
  3629. await deployServer(
  3630. backend,
  3631. { platform: "linux", arch: "arm64" },
  3632. {
  3633. force: false,
  3634. remoteCdnBaseUrl: cdnServer.baseUrl,
  3635. remoteCacheDir,
  3636. },
  3637. );
  3638. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/agents/glm/zcode.cjs.new")).toBe(
  3639. true,
  3640. );
  3641. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(2);
  3642. } finally {
  3643. await cdnServer.close();
  3644. }
  3645. });
  3646. it("同一 App 版本内 server-bundle SHA 更新时应下载并上传新制品", async () => {
  3647. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3648. tempDirs.push(rootDir);
  3649. const mockCdnDir = join(rootDir, "mock-cdn");
  3650. const cdnRoot = join(rootDir, "cdn");
  3651. const remoteCacheDir = join(rootDir, "remote-cache");
  3652. await stageRemoteRuntimeRelease(mockCdnDir);
  3653. const initialManifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  3654. const initialServer = findManifestComponent(initialManifest, "server-bundle");
  3655. const legacyServerCacheDir = join(
  3656. remoteCacheDir,
  3657. "components",
  3658. "server-bundle",
  3659. initialServer.version,
  3660. );
  3661. await mkdir(legacyServerCacheDir, { recursive: true });
  3662. await writeFile(join(legacyServerCacheDir, ".ready"), "ready\n", "utf8");
  3663. await writeFile(
  3664. join(legacyServerCacheDir, "zcode-server.cjs"),
  3665. "// stale semantic-version server cache\n",
  3666. "utf8",
  3667. );
  3668. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  3669. addMatchingGlmArtifactIdentity(remoteFiles, initialManifest, "linux-arm64");
  3670. const backend = new FakeRemoteBackend(remoteFiles);
  3671. const cdnServer = await createStaticFileServer(cdnRoot);
  3672. try {
  3673. await deployServer(
  3674. backend,
  3675. { platform: "linux", arch: "arm64" },
  3676. { remoteCdnBaseUrl: cdnServer.baseUrl, remoteCacheDir },
  3677. );
  3678. expect(hasUploadForStagingTarget(backend, "~/.zcode/server/zcode-server.cjs.new")).toBe(true);
  3679. const initialServerUpload = findUploadForStagingTarget(
  3680. backend,
  3681. "~/.zcode/server/zcode-server.cjs.new",
  3682. );
  3683. await expect(readFile(initialServerUpload?.localPath ?? "", "utf8")).resolves.not.toContain(
  3684. "stale semantic-version server cache",
  3685. );
  3686. backend.uploads.splice(0);
  3687. addMatchingServerBundleArtifactIdentity(remoteFiles, initialManifest, "linux-arm64");
  3688. backend.remoteFiles.set(
  3689. "~/.zcode/server/.asset-components/server-bundle.json",
  3690. remoteFiles["~/.zcode/server/.asset-components/server-bundle.json"] ?? "",
  3691. );
  3692. await writeFile(
  3693. join(mockCdnDir, "releases", ZCODE_VERSION, "server", "zcode-server.cjs"),
  3694. "// server bundle republished under the same App version\n",
  3695. "utf8",
  3696. );
  3697. const updatedManifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  3698. const updatedServer = findManifestComponent(updatedManifest, "server-bundle");
  3699. expect(updatedServer.version).toBe(initialServer.version);
  3700. expect(updatedServer.sha256).not.toBe(initialServer.sha256);
  3701. await deployServer(
  3702. backend,
  3703. { platform: "linux", arch: "arm64" },
  3704. { remoteCdnBaseUrl: cdnServer.baseUrl, remoteCacheDir },
  3705. );
  3706. const serverUpload = findUploadForStagingTarget(
  3707. backend,
  3708. "~/.zcode/server/zcode-server.cjs.new",
  3709. );
  3710. expect(serverUpload).toBeDefined();
  3711. await expect(readFile(serverUpload?.localPath ?? "", "utf8")).resolves.toContain(
  3712. "server bundle republished under the same App version",
  3713. );
  3714. expect(
  3715. cdnServer.getRequestCount(toComponentArtifactRequestPath(updatedServer.artifactPath)),
  3716. ).toBe(2);
  3717. } finally {
  3718. await cdnServer.close();
  3719. }
  3720. });
  3721. it("并发 GLM SHA 检查应共享一次 fresh manifest 请求", async () => {
  3722. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3723. tempDirs.push(rootDir);
  3724. const mockCdnDir = join(rootDir, "mock-cdn");
  3725. const cdnRoot = join(rootDir, "cdn");
  3726. const remoteCacheDir = join(rootDir, "remote-cache");
  3727. await stageRemoteRuntimeRelease(mockCdnDir);
  3728. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  3729. const createBackend = (): FakeRemoteBackend => {
  3730. const remoteFiles = createFullyDeployedRemoteFiles("linux-arm64");
  3731. addMatchingGlmAndServerArtifactIdentities(remoteFiles, manifest, "linux-arm64");
  3732. return new FakeRemoteBackend(remoteFiles);
  3733. };
  3734. const cdnServer = await createStaticFileServer(cdnRoot);
  3735. try {
  3736. await Promise.all([
  3737. deployServer(
  3738. createBackend(),
  3739. { platform: "linux", arch: "arm64" },
  3740. { remoteCdnBaseUrl: cdnServer.baseUrl, remoteCacheDir },
  3741. ),
  3742. deployServer(
  3743. createBackend(),
  3744. { platform: "linux", arch: "arm64" },
  3745. { remoteCdnBaseUrl: cdnServer.baseUrl, remoteCacheDir },
  3746. ),
  3747. ]);
  3748. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(1);
  3749. // warm cache 下的第二轮并发也只能创建一个 refresh task。
  3750. await Promise.all([
  3751. deployServer(
  3752. createBackend(),
  3753. { platform: "linux", arch: "arm64" },
  3754. { remoteCdnBaseUrl: cdnServer.baseUrl, remoteCacheDir },
  3755. ),
  3756. deployServer(
  3757. createBackend(),
  3758. { platform: "linux", arch: "arm64" },
  3759. { remoteCdnBaseUrl: cdnServer.baseUrl, remoteCacheDir },
  3760. ),
  3761. ]);
  3762. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(2);
  3763. // remote-download 也必须让身份判断与实际安装共享同一个 manifest 请求。
  3764. await Promise.all([
  3765. deployServer(
  3766. createBackend(),
  3767. { platform: "linux", arch: "arm64" },
  3768. {
  3769. assetInstallMode: "remote-download",
  3770. remoteCdnBaseUrl: cdnServer.baseUrl,
  3771. },
  3772. ),
  3773. deployServer(
  3774. createBackend(),
  3775. { platform: "linux", arch: "arm64" },
  3776. {
  3777. assetInstallMode: "remote-download",
  3778. remoteCdnBaseUrl: cdnServer.baseUrl,
  3779. },
  3780. ),
  3781. ]);
  3782. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(3);
  3783. } finally {
  3784. await cdnServer.close();
  3785. }
  3786. });
  3787. it("并发 GLM 部署应按各自 manifest SHA 快照隔离 release", async () => {
  3788. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3789. tempDirs.push(rootDir);
  3790. const mockCdnDir = join(rootDir, "mock-cdn");
  3791. const cdnRoot = join(rootDir, "cdn");
  3792. const remoteCacheDir = join(rootDir, "remote-cache");
  3793. await stageRemoteRuntimeRelease(mockCdnDir);
  3794. const initialManifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  3795. const initialGlm = initialManifest.components.find((component) => component.id === "glm");
  3796. if (!initialGlm) {
  3797. throw new Error("missing glm component in staged manifest");
  3798. }
  3799. const pinnedArtifactPath = initialGlm.artifactPath.replace(/\.tar\.gz$/u, "-pinned.tar.gz");
  3800. await cp(join(cdnRoot, initialGlm.artifactPath), join(cdnRoot, pinnedArtifactPath));
  3801. const pinnedInitialManifest: RemoteComponentManifest = {
  3802. ...initialManifest,
  3803. components: initialManifest.components.map((component) =>
  3804. component.id === "glm" ? { ...component, artifactPath: pinnedArtifactPath } : component,
  3805. ),
  3806. };
  3807. await writeFile(
  3808. join(mockCdnDir, "releases", ZCODE_VERSION, "glm", "linux-arm64", "zcode.cjs"),
  3809. "new GLM bytes under the same semantic version",
  3810. "utf8",
  3811. );
  3812. const updatedManifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  3813. const updatedGlm = updatedManifest.components.find((component) => component.id === "glm");
  3814. if (!updatedGlm) {
  3815. throw new Error("missing updated glm component in staged manifest");
  3816. }
  3817. expect(updatedGlm.version).toBe(initialGlm.version);
  3818. expect(updatedGlm.sha256).not.toBe(initialGlm.sha256);
  3819. const cdnServer = await createStaticFileServer(cdnRoot);
  3820. try {
  3821. const [initialReleaseDir, updatedReleaseDir] = await Promise.all([
  3822. ensureRemoteReleaseDirFromCdn(
  3823. {
  3824. remoteCdnBaseUrl: cdnServer.baseUrl,
  3825. remoteCacheDir,
  3826. version: ZCODE_VERSION,
  3827. platformArch: "linux-arm64",
  3828. componentIds: ["glm"],
  3829. manifestRef: {
  3830. manifest: pinnedInitialManifest,
  3831. releaseBaseCandidatesForComponents: [`${cdnServer.baseUrl}/${ZCODE_VERSION}`],
  3832. },
  3833. },
  3834. { log: () => {}, logWarn: () => {} },
  3835. ),
  3836. ensureRemoteReleaseDirFromCdn(
  3837. {
  3838. remoteCdnBaseUrl: cdnServer.baseUrl,
  3839. remoteCacheDir,
  3840. version: ZCODE_VERSION,
  3841. platformArch: "linux-arm64",
  3842. componentIds: ["glm"],
  3843. manifestRef: {
  3844. manifest: updatedManifest,
  3845. releaseBaseCandidatesForComponents: [`${cdnServer.baseUrl}/${ZCODE_VERSION}`],
  3846. },
  3847. },
  3848. { log: () => {}, logWarn: () => {} },
  3849. ),
  3850. ]);
  3851. expect(initialReleaseDir).toContain(initialGlm.sha256);
  3852. expect(updatedReleaseDir).toContain(updatedGlm.sha256);
  3853. expect(initialReleaseDir).not.toBe(updatedReleaseDir);
  3854. expect(cdnServer.getRequestCount(toComponentArtifactRequestPath(pinnedArtifactPath))).toBe(1);
  3855. expect(
  3856. cdnServer.getRequestCount(toComponentArtifactRequestPath(updatedGlm.artifactPath)),
  3857. ).toBe(1);
  3858. } finally {
  3859. await cdnServer.close();
  3860. }
  3861. });
  3862. it("同一 GLM SHA 的普通下载与强制刷新并发时应复用一次已校验下载", async () => {
  3863. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3864. tempDirs.push(rootDir);
  3865. const mockCdnDir = join(rootDir, "mock-cdn");
  3866. const cdnRoot = join(rootDir, "cdn");
  3867. const remoteCacheDir = join(rootDir, "remote-cache");
  3868. await stageRemoteRuntimeRelease(mockCdnDir);
  3869. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  3870. const glm = findManifestComponent(manifest, "glm");
  3871. const requiredPluginPath = OFFICIAL_PLUGIN_REQUIRED_RELATIVE_PATHS[0];
  3872. if (!requiredPluginPath) {
  3873. throw new Error("missing required official plugin test path");
  3874. }
  3875. const artifactRequestPath = toComponentArtifactRequestPath(glm.artifactPath);
  3876. let releaseArtifactResponse: (() => void) | undefined;
  3877. const artifactResponseGate = new Promise<void>((resolve) => {
  3878. releaseArtifactResponse = resolve;
  3879. });
  3880. const cdnServer = await createStaticFileServer(cdnRoot, {
  3881. responseGates: new Map([[artifactRequestPath, artifactResponseGate]]),
  3882. });
  3883. const releaseOptions = {
  3884. remoteCdnBaseUrl: cdnServer.baseUrl,
  3885. remoteCacheDir,
  3886. version: ZCODE_VERSION,
  3887. platformArch: "linux-arm64",
  3888. componentIds: ["glm"],
  3889. requiredReleasePaths: [
  3890. "glm/linux-arm64/zcode.cjs",
  3891. ...OFFICIAL_PLUGIN_REQUIRED_RELATIVE_PATHS.map(
  3892. (relativePath) => `glm/linux-arm64/packages/${relativePath}`,
  3893. ),
  3894. ],
  3895. manifestRef: {
  3896. manifest,
  3897. releaseBaseCandidatesForComponents: [`${cdnServer.baseUrl}/${ZCODE_VERSION}`],
  3898. },
  3899. };
  3900. const loggers = { log: () => {}, logWarn: () => {} };
  3901. try {
  3902. const reuseReleasePromise = ensureRemoteReleaseDirFromCdn(releaseOptions, loggers);
  3903. await vi.waitFor(() => {
  3904. expect(cdnServer.getRequestCount(artifactRequestPath)).toBe(1);
  3905. });
  3906. // Bugfix 验证:普通下载已持有同一 SHA component 锁时,force 应复用这次
  3907. // 已校验下载;拆分锁会让两个任务并发替换同一目录并产生重复 CDN 请求。
  3908. const forceReleasePromise = ensureRemoteReleaseDirFromCdn(
  3909. { ...releaseOptions, forceRefresh: true },
  3910. loggers,
  3911. );
  3912. releaseArtifactResponse?.();
  3913. const [reuseReleaseDir, forceReleaseDir] = await Promise.all([
  3914. reuseReleasePromise,
  3915. forceReleasePromise,
  3916. ]);
  3917. expect(forceReleaseDir).toBe(reuseReleaseDir);
  3918. expect(forceReleaseDir).toContain(glm.sha256);
  3919. expect(cdnServer.getRequestCount(artifactRequestPath)).toBe(1);
  3920. await expect(
  3921. readFile(join(forceReleaseDir, "glm", "linux-arm64", "zcode.cjs"), "utf8"),
  3922. ).resolves.toBe("glm bundle");
  3923. await expect(
  3924. readFile(
  3925. join(forceReleaseDir, "glm", "linux-arm64", "packages", requiredPluginPath),
  3926. "utf8",
  3927. ),
  3928. ).resolves.toBe(`glm official plugin ${requiredPluginPath}`);
  3929. } finally {
  3930. releaseArtifactResponse?.();
  3931. await cdnServer.close();
  3932. }
  3933. });
  3934. it("生产态组件 cache 未命中时应从旧 release cache 迁移相同内容组件", async () => {
  3935. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  3936. tempDirs.push(rootDir);
  3937. const mockCdnDir = join(rootDir, "mock-cdn");
  3938. const cdnRoot = join(rootDir, "cdn");
  3939. const remoteCacheDir = join(rootDir, "remote-cache");
  3940. const platformKey = "linux-arm64";
  3941. await stageRemoteRuntimeRelease(mockCdnDir);
  3942. const sourceReleaseDir = join(mockCdnDir, "releases", ZCODE_VERSION);
  3943. const legacyReleaseDir = join(remoteCacheDir, "releases", "1.2.9", platformKey);
  3944. await cp(sourceReleaseDir, legacyReleaseDir, { recursive: true });
  3945. await writeFile(join(legacyReleaseDir, ".remote-assets-ready"), "legacy-ready\n", "utf8");
  3946. const nodeRuntimeSourceDir = join(sourceReleaseDir, "node", platformKey);
  3947. const nodeRuntimeContentHash = await computePathContentSha256(nodeRuntimeSourceDir);
  3948. const nodeRuntimeSemanticVersion = "v24.10.0";
  3949. const migratedNodeRuntimeVersion = `v24.10.0+${nodeRuntimeContentHash.slice(0, 12)}`;
  3950. const missingNodeRuntimeArtifactPath = `components/${platformKey}/node-runtime/${migratedNodeRuntimeVersion}.tar.gz`;
  3951. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot, {
  3952. platformKey,
  3953. mutateManifest: (rawManifest) => ({
  3954. ...rawManifest,
  3955. components: rawManifest.components.map((component) =>
  3956. component.id === "node-runtime"
  3957. ? {
  3958. ...component,
  3959. version: migratedNodeRuntimeVersion,
  3960. artifactPath: missingNodeRuntimeArtifactPath,
  3961. }
  3962. : component,
  3963. ),
  3964. }),
  3965. });
  3966. const nodeRuntime = manifest.components.find((component) => component.id === "node-runtime");
  3967. if (!nodeRuntime) {
  3968. throw new Error("missing node-runtime component in staged manifest");
  3969. }
  3970. const glm = manifest.components.find((component) => component.id === "glm");
  3971. if (!glm) {
  3972. throw new Error("missing glm component in staged manifest");
  3973. }
  3974. const cdnServer = await createStaticFileServer(cdnRoot);
  3975. try {
  3976. await expect(
  3977. ensureRemoteReleaseDirFromCdn(
  3978. {
  3979. remoteCdnBaseUrl: cdnServer.baseUrl,
  3980. remoteCacheDir,
  3981. version: ZCODE_VERSION,
  3982. platformArch: platformKey,
  3983. },
  3984. { log: () => {}, logWarn: () => {} },
  3985. ),
  3986. ).resolves.toBe(
  3987. join(remoteCacheDir, "releases", ZCODE_VERSION, platformKey, "glm-content", glm.sha256),
  3988. );
  3989. expect(
  3990. cdnServer.getRequestCount(toVersionedArtifactRequestPath(nodeRuntime.artifactPath)),
  3991. ).toBe(0);
  3992. await expect(
  3993. readFile(
  3994. join(
  3995. remoteCacheDir,
  3996. "components",
  3997. "node-runtime",
  3998. platformKey,
  3999. nodeRuntimeSemanticVersion,
  4000. ".ready",
  4001. ),
  4002. "utf8",
  4003. ),
  4004. ).resolves.toBeTruthy();
  4005. } finally {
  4006. await cdnServer.close();
  4007. }
  4008. });
  4009. it("生产态 GLM 不应按语义版本复用旧 hash 目录组件", async () => {
  4010. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  4011. tempDirs.push(rootDir);
  4012. const mockCdnDir = join(rootDir, "mock-cdn");
  4013. const cdnRoot = join(rootDir, "cdn");
  4014. const remoteCacheDir = join(rootDir, "remote-cache");
  4015. const platformKey = "linux-arm64";
  4016. await stageRemoteRuntimeRelease(mockCdnDir);
  4017. const sourceReleaseDir = join(mockCdnDir, "releases", ZCODE_VERSION);
  4018. const oldGlmComponentVersion = `${LEGACY_REMOTE_TEST_AGENT_RUNTIME.glm.version}-glm+legacyhash001`;
  4019. const oldGlmComponentDir = join(
  4020. remoteCacheDir,
  4021. "components",
  4022. "glm",
  4023. platformKey,
  4024. oldGlmComponentVersion,
  4025. );
  4026. await mkdir(oldGlmComponentDir, { recursive: true });
  4027. await copySourcePathContentToDir(
  4028. join(sourceReleaseDir, "glm", platformKey),
  4029. oldGlmComponentDir,
  4030. );
  4031. await writeFile(join(oldGlmComponentDir, ".ready"), "old-component-ready\n", "utf8");
  4032. const semanticGlmComponentVersion = `${LEGACY_REMOTE_TEST_AGENT_RUNTIME.glm.version}-glm`;
  4033. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot, {
  4034. platformKey,
  4035. mutateManifest: (rawManifest) => ({
  4036. ...rawManifest,
  4037. components: rawManifest.components.map((component) =>
  4038. component.id === "glm"
  4039. ? {
  4040. ...component,
  4041. version: semanticGlmComponentVersion,
  4042. }
  4043. : component,
  4044. ),
  4045. }),
  4046. });
  4047. const glm = manifest.components.find((component) => component.id === "glm");
  4048. if (!glm) {
  4049. throw new Error("missing glm component in staged manifest");
  4050. }
  4051. const cdnServer = await createStaticFileServer(cdnRoot);
  4052. try {
  4053. await expect(
  4054. ensureRemoteReleaseDirFromCdn(
  4055. {
  4056. remoteCdnBaseUrl: cdnServer.baseUrl,
  4057. remoteCacheDir,
  4058. version: ZCODE_VERSION,
  4059. platformArch: platformKey,
  4060. componentIds: ["glm"],
  4061. },
  4062. { log: () => {}, logWarn: () => {} },
  4063. ),
  4064. ).resolves.toBe(
  4065. join(remoteCacheDir, "releases", ZCODE_VERSION, platformKey, "glm-content", glm.sha256),
  4066. );
  4067. expect(cdnServer.getRequestCount(toComponentArtifactRequestPath(glm.artifactPath))).toBe(1);
  4068. await expect(
  4069. readFile(
  4070. join(remoteCacheDir, "components", "glm", platformKey, glm.sha256, ".ready"),
  4071. "utf8",
  4072. ),
  4073. ).resolves.toBeTruthy();
  4074. } finally {
  4075. await cdnServer.close();
  4076. }
  4077. });
  4078. it("生产态不同 remoteCacheDir 并发预热时不应共享同一把下载锁", async () => {
  4079. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  4080. tempDirs.push(rootDir);
  4081. const mockCdnDir = join(rootDir, "mock-cdn");
  4082. const cdnRoot = join(rootDir, "cdn");
  4083. const remoteCacheDirA = join(rootDir, "remote-cache-a");
  4084. const remoteCacheDirB = join(rootDir, "remote-cache-b");
  4085. await stageRemoteRuntimeRelease(mockCdnDir);
  4086. const manifest = await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  4087. const cdnServer = await createStaticFileServer(cdnRoot);
  4088. const serverBundle = manifest.components.find((component) => component.id === "server-bundle");
  4089. if (!serverBundle) {
  4090. throw new Error("missing server-bundle component in staged manifest");
  4091. }
  4092. try {
  4093. // Bugfix: 之前锁 key 没有带 remoteCacheDir,导致不同缓存目录会误共享同一 Promise。
  4094. // 这里并发预热两个 cache,断言应各自返回独立目录并各自下载一次。
  4095. const [releaseDirA, releaseDirB] = await Promise.all([
  4096. ensureRemoteReleaseDirFromCdn(
  4097. {
  4098. remoteCdnBaseUrl: cdnServer.baseUrl,
  4099. remoteCacheDir: remoteCacheDirA,
  4100. version: ZCODE_VERSION,
  4101. platformArch: "linux-arm64",
  4102. },
  4103. { log: () => {}, logWarn: () => {} },
  4104. ),
  4105. ensureRemoteReleaseDirFromCdn(
  4106. {
  4107. remoteCdnBaseUrl: cdnServer.baseUrl,
  4108. remoteCacheDir: remoteCacheDirB,
  4109. version: ZCODE_VERSION,
  4110. platformArch: "linux-arm64",
  4111. },
  4112. { log: () => {}, logWarn: () => {} },
  4113. ),
  4114. ]);
  4115. expect(releaseDirA).not.toBe(releaseDirB);
  4116. expect(releaseDirA).toContain("remote-cache-a");
  4117. expect(releaseDirB).toContain("remote-cache-b");
  4118. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/manifest-linux-arm64.json`)).toBe(2);
  4119. expect(
  4120. cdnServer.getRequestCount(toVersionedArtifactRequestPath(serverBundle.artifactPath)),
  4121. ).toBe(0);
  4122. expect(
  4123. cdnServer.getRequestCount(toComponentArtifactRequestPath(serverBundle.artifactPath)),
  4124. ).toBe(2);
  4125. } finally {
  4126. await cdnServer.close();
  4127. }
  4128. });
  4129. it("生产态 manifest mount 路径校验失败时应抛出错误", async () => {
  4130. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  4131. tempDirs.push(rootDir);
  4132. const mockCdnDir = join(rootDir, "mock-cdn");
  4133. const cdnRoot = join(rootDir, "cdn");
  4134. const remoteCacheDir = join(rootDir, "remote-cache");
  4135. await stageRemoteRuntimeRelease(mockCdnDir);
  4136. await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot, {
  4137. mutateManifest: (manifest) => ({
  4138. ...manifest,
  4139. components: manifest.components.map((component) =>
  4140. component.id === "server-bundle"
  4141. ? { ...component, mount: "../escape-release-root" }
  4142. : component,
  4143. ),
  4144. }),
  4145. });
  4146. const cdnServer = await createStaticFileServer(cdnRoot);
  4147. try {
  4148. await expect(
  4149. deployServer(
  4150. new FakeRemoteBackend({
  4151. "~/.zcode/server/agents/codex/.version": "0.0.0\n",
  4152. }),
  4153. { platform: "linux", arch: "arm64" },
  4154. {
  4155. force: false,
  4156. remoteCdnBaseUrl: cdnServer.baseUrl,
  4157. remoteCacheDir,
  4158. },
  4159. ),
  4160. ).rejects.toThrow(/mount|白名单|路径|path|invalid|escape/iu);
  4161. expect(cdnServer.getRequestCount(`/${ZCODE_VERSION}/remote-assets-linux-arm64.tar.gz`)).toBe(
  4162. 0,
  4163. );
  4164. } finally {
  4165. await cdnServer.close();
  4166. }
  4167. });
  4168. it("生产态下载 remote 资源时应输出百分比/体积/速度进度日志", async () => {
  4169. const rootDir = await mkdtemp(join(tmpdir(), "zcode-remote-deploy-"));
  4170. tempDirs.push(rootDir);
  4171. const mockCdnDir = join(rootDir, "mock-cdn");
  4172. const cdnRoot = join(rootDir, "cdn");
  4173. const remoteCacheDir = join(rootDir, "remote-cache");
  4174. await stageRemoteRuntimeRelease(mockCdnDir);
  4175. await stageRemoteComponentArtifacts(mockCdnDir, cdnRoot);
  4176. const cdnServer = await createStaticFileServer(cdnRoot);
  4177. const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  4178. try {
  4179. await deployServer(
  4180. new FakeRemoteBackend({
  4181. "~/.zcode/server/agents/codex/.version": "0.0.0\n",
  4182. }),
  4183. { platform: "linux", arch: "arm64" },
  4184. {
  4185. force: false,
  4186. remoteCdnBaseUrl: cdnServer.baseUrl,
  4187. remoteCacheDir,
  4188. },
  4189. );
  4190. const allLogLines = logSpy.mock.calls.map((args) => args.map((arg) => String(arg)).join(" "));
  4191. const progressLine = allLogLines.find((line) => line.includes("download progress:"));
  4192. expect(progressLine).toBeTruthy();
  4193. expect(progressLine).toMatch(/\d+(?:\.\d+)?%/u);
  4194. expect(progressLine).toMatch(/\d+(?:\.\d+)?\/\d+(?:\.\d+)?\s*MB/u);
  4195. expect(progressLine).toMatch(/\d+(?:\.\d+)?\s*MB\/s/u);
  4196. } finally {
  4197. logSpy.mockRestore();
  4198. await cdnServer.close();
  4199. }
  4200. });
  4201. it("Windows 原生 remote 应显式报不支持", async () => {
  4202. const backend = new FakeRemoteBackend();
  4203. await expect(
  4204. deployServer(
  4205. backend,
  4206. { platform: "win32", arch: "x64" },
  4207. {
  4208. force: false,
  4209. mockCdnDir: "/tmp/unused",
  4210. },
  4211. ),
  4212. ).rejects.toThrow(/暂不支持 Windows 原生远程主机/);
  4213. });
  4214. });