remoteDeploy.test.ts 162 KB

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