plugins.test.ts 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990
  1. import { execFile } from "node:child_process";
  2. import { setTimeout as delay } from "node:timers/promises";
  3. import { promisify } from "node:util";
  4. import { createHash } from "node:crypto";
  5. import { existsSync } from "node:fs";
  6. import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
  7. import { createServer, type Server } from "node:http";
  8. import { tmpdir } from "node:os";
  9. import { basename, dirname, join } from "node:path";
  10. import { fileURLToPath } from "node:url";
  11. import { createConfig } from "@zcode/adapters/config";
  12. import { DEFAULT_ENABLED_OFFICIAL_PLUGIN_IDS } from "@zcode/shared";
  13. import { ZCODE_PLUGIN_HOST_COMMAND } from "@zcode/contracts";
  14. import type { Logger, PluginDiscoverRequest } from "@zcode/contracts";
  15. import { describe, expect, it, vi } from "vitest";
  16. import { resolveStartupPlugins } from "../src/app/startup-marks.js";
  17. import {
  18. createOfficialPluginPreparation,
  19. findMissingOfficialPluginSeedPaths,
  20. resolveOfficialPluginRoots,
  21. } from "../src/app/bundled-plugins.js";
  22. import {
  23. OFFICIAL_BROWSER_USE_REQUIRED_SEED_PATHS,
  24. OFFICIAL_PLUGIN_DEFINITIONS,
  25. } from "../src/app/official-plugin-definitions.js";
  26. import { createPluginFacadeForApp } from "../src/app/plugin-facade.js";
  27. import type { ZCodeAppOptions } from "../src/app/types.js";
  28. import {
  29. configureZCodePlugin,
  30. describeZCodePlugin,
  31. enrichCachedClaudeMarketplaceIconsForOverview,
  32. getZCodePluginsOverview,
  33. installZCodeMarketplacePlugin,
  34. listZCodePlugins,
  35. resolveZCodePlugins,
  36. resetZCodePluginConfig,
  37. resolveMarketplaceRefreshTargetIds,
  38. restoreBuiltinPlugin,
  39. setZCodePluginEnabled,
  40. uninstallZCodeMarketplacePlugin,
  41. updateZCodePluginMarketplace,
  42. validateZCodePlugin,
  43. isWorkspacePluginConfigPath,
  44. } from "../src/plugins.js";
  45. import { StartupTimer } from "../src/startup-logging.js";
  46. const IOS_SIMULATOR_PLUGIN_ID = "ios-simulator@zcode-plugins-official";
  47. it("Settings 默认启用集合与 CLI 的官方插件声明一致", () => {
  48. expect([...DEFAULT_ENABLED_OFFICIAL_PLUGIN_IDS].sort()).toEqual(
  49. OFFICIAL_PLUGIN_DEFINITIONS.filter((definition) => definition.defaultEnabled)
  50. .map((definition) => `${definition.name}@zcode-plugins-official`)
  51. .sort(),
  52. );
  53. });
  54. // 产品决策(2026-09-11):电脑控制回退为默认关闭,首启不再注入 computer-use 工具集与
  55. // Helper 依赖。上面那条只保证两处名单同步,不阻止有人重新把 defaultEnabled 标回 true,
  56. // 所以这里单独把 CUA 的默认态钉住。
  57. it("computer-use 默认不启用(电脑控制需用户在设置页显式开启)", () => {
  58. const cua = OFFICIAL_PLUGIN_DEFINITIONS.find((definition) => definition.name === "computer-use");
  59. expect(cua).toBeDefined();
  60. expect(cua?.defaultEnabled ?? false).toBe(false);
  61. expect(DEFAULT_ENABLED_OFFICIAL_PLUGIN_IDS.has("computer-use@zcode-plugins-official")).toBe(
  62. false,
  63. );
  64. });
  65. it("design 默认关闭,等待用户安装或启用", () => {
  66. const design = OFFICIAL_PLUGIN_DEFINITIONS.find((definition) => definition.name === "design");
  67. expect(design).toBeDefined();
  68. expect(design?.defaultEnabled ?? false).toBe(false);
  69. expect(DEFAULT_ENABLED_OFFICIAL_PLUGIN_IDS.has("design@zcode-plugins-official")).toBe(false);
  70. });
  71. const ANDROID_EMULATOR_PLUGIN_ID = "android-emulator@zcode-plugins-official";
  72. const IOS_SIMULATOR_MCP_ID = "plugin:ios-simulator:ios-simulator";
  73. const ANDROID_EMULATOR_MCP_ID = "plugin:android-emulator:android-emulator";
  74. const BROWSER_USE_PLUGIN_ID = "browser-use@zcode-plugins-official";
  75. const DOCUMENTS_PLUGIN_ID = "documents@zcode-plugins-official";
  76. const RESTORE_LEGACY_SESSIONS_PLUGIN_ID = "restore-legacy-sessions@zcode-plugins-official";
  77. const SKILL_CREATOR_PLUGIN_ID = "skill-creator@zcode-plugins-official";
  78. function createNoopStartupTimer(): StartupTimer {
  79. const noop = () => {};
  80. const logger: Logger = {
  81. debug: noop,
  82. info: noop,
  83. warn: noop,
  84. error: noop,
  85. child: () => logger,
  86. };
  87. return new StartupTimer(logger, {});
  88. }
  89. const OFFICIAL_PLUGIN_CACHE_PATH = join(
  90. "cache",
  91. "zcode-plugins-official",
  92. "ios-simulator",
  93. "0.1.0",
  94. );
  95. const OFFICIAL_ANDROID_PLUGIN_CACHE_PATH = join(
  96. "cache",
  97. "zcode-plugins-official",
  98. "android-emulator",
  99. "0.1.1",
  100. );
  101. const OFFICIAL_RESTORE_LEGACY_SESSIONS_PLUGIN_CACHE_PATH = join(
  102. "cache",
  103. "zcode-plugins-official",
  104. "restore-legacy-sessions",
  105. "0.1.0",
  106. );
  107. const OFFICIAL_SKILL_CREATOR_PLUGIN_CACHE_PATH = join(
  108. "cache",
  109. "zcode-plugins-official",
  110. "skill-creator",
  111. "0.1.0",
  112. );
  113. const BUNDLED_PLUGIN_DIST_PATH = fileURLToPath(
  114. new URL("../../ios-simulator-plugin/dist/mcp/server.js", import.meta.url),
  115. );
  116. const BUNDLED_ANDROID_PLUGIN_DIST_PATH = fileURLToPath(
  117. new URL("../../android-emulator-plugin/dist/mcp/server.js", import.meta.url),
  118. );
  119. describe("ZCode plugins", () => {
  120. it("uses the existing Runtime identity for shared startup and facade discovery", async () => {
  121. const root = await mkdtemp(join(tmpdir(), "zcode-runtime-plugin-scope-"));
  122. const discoverPlugins = vi.fn(async (_request: PluginDiscoverRequest) => ({
  123. commandRoots: [],
  124. diagnostics: [],
  125. hooks: {},
  126. mcpServers: {},
  127. plugins: [],
  128. skillRoots: [],
  129. }));
  130. const options = {
  131. env: {},
  132. pluginStorageRoot: join(root, "plugins"),
  133. pluginDiscovery: { discoverPlugins },
  134. pluginPreparation: {
  135. startupDegraded: false,
  136. resolvePlugins: async (resolve: () => ReturnType<typeof discoverPlugins>) =>
  137. await resolve(),
  138. signal: new AbortController().signal,
  139. prepare: async () => [],
  140. invalidate() {},
  141. async dispose() {},
  142. },
  143. runtimeConfig: {
  144. memory: { workspaceIdentity: "remote-workspace" },
  145. remoteSessionId: "attachment-one",
  146. },
  147. };
  148. try {
  149. const configResult = createConfig({ env: {}, skipUserConfig: true, workingDirectory: root });
  150. await resolveStartupPlugins({
  151. cliStorageRoot: join(root, "cli"),
  152. configResult,
  153. options,
  154. startupTimer: createNoopStartupTimer(),
  155. workingDirectory: root,
  156. });
  157. const facade = createPluginFacadeForApp({
  158. configResult,
  159. options: options as ZCodeAppOptions,
  160. workingDirectory: root,
  161. });
  162. await facade.listPlugins();
  163. expect(discoverPlugins).toHaveBeenCalledTimes(2);
  164. for (const call of discoverPlugins.mock.calls) {
  165. expect(call[0]).toMatchObject({
  166. workingDirectory: root,
  167. workspaceIdentity: "remote-workspace",
  168. remoteSessionId: "attachment-one",
  169. });
  170. }
  171. } finally {
  172. await rm(root, { recursive: true, force: true });
  173. }
  174. });
  175. it("starts cached Claude icon migration without blocking overview callers", async () => {
  176. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-icon-migration-"));
  177. const pluginStorageRoot = join(root, "plugins");
  178. const marketplaceRoot = join(pluginStorageRoot, "marketplaces", "claude-plugins-official");
  179. try {
  180. await mkdir(marketplaceRoot, { recursive: true });
  181. await writeFile(
  182. join(marketplaceRoot, "marketplace.json"),
  183. JSON.stringify({
  184. name: "claude-plugins-official",
  185. plugins: [{ name: "figma", source: "./figma" }],
  186. }),
  187. );
  188. let resolveFetch!: (response: Response) => void;
  189. vi.stubGlobal(
  190. "fetch",
  191. vi.fn(
  192. () =>
  193. new Promise<Response>((resolve) => {
  194. resolveFetch = resolve;
  195. }),
  196. ),
  197. );
  198. expect(
  199. enrichCachedClaudeMarketplaceIconsForOverview({
  200. env: {},
  201. pluginStorageRoot,
  202. skipUserConfig: true,
  203. workingDirectory: root,
  204. }),
  205. ).toBeUndefined();
  206. resolveFetch(
  207. new Response(
  208. JSON.stringify([{ name: "figma", icon: "figma/icon.png", mimeType: "image/png" }]),
  209. { status: 200 },
  210. ),
  211. );
  212. await vi.waitFor(async () => {
  213. const saved = JSON.parse(
  214. await readFile(join(marketplaceRoot, "marketplace.json"), "utf8"),
  215. ) as { plugins: Array<{ icon?: string }> };
  216. expect(saved.plugins[0]?.icon).toBe(
  217. "https://cdn-zcode.z.ai/zcode/official-plugin/assets/figma/icon.png",
  218. );
  219. });
  220. } finally {
  221. vi.unstubAllGlobals();
  222. await rm(root, { force: true, recursive: true });
  223. }
  224. });
  225. it("declares the ui component type exactly for bundled plugins with UI surfaces", async () => {
  226. const packagesRoot = fileURLToPath(new URL("../../", import.meta.url));
  227. for (const plugin of OFFICIAL_PLUGIN_DEFINITIONS) {
  228. const packageRoot = join(packagesRoot, basename(plugin.rootCandidates[0] ?? ""));
  229. const pluginManifest = JSON.parse(
  230. await readFile(join(packageRoot, ".zcode-plugin", "plugin.json"), "utf8"),
  231. ) as { ui?: { surfaces?: unknown[] } };
  232. // 卸载后的可恢复条目没有运行时信息,商店只能靠定义里的 componentTypes 归入「UI 插件」。
  233. expect(plugin.componentTypes?.includes("ui") ?? false, plugin.name).toBe(
  234. (pluginManifest.ui?.surfaces?.length ?? 0) > 0,
  235. );
  236. }
  237. });
  238. it("rejects an incomplete Browser Use filesystem or SEA seed", () => {
  239. const browserUse = OFFICIAL_PLUGIN_DEFINITIONS.find((plugin) => plugin.name === "browser-use");
  240. if (!browserUse) throw new Error("missing Browser Use official plugin definition");
  241. expect(browserUse.requiredSeedPaths).toEqual(OFFICIAL_BROWSER_USE_REQUIRED_SEED_PATHS);
  242. expect(browserUse.requiredSeedPaths).toContain("docs/recording.md");
  243. expect(
  244. findMissingOfficialPluginSeedPaths(browserUse, [
  245. ...OFFICIAL_BROWSER_USE_REQUIRED_SEED_PATHS.slice(0, -1).map((path) => ({ path })),
  246. ]),
  247. ).toEqual([OFFICIAL_BROWSER_USE_REQUIRED_SEED_PATHS.at(-1)]);
  248. });
  249. it.each([undefined, true, false])(
  250. "resolves design default and explicit preference: %s",
  251. async (enabled) => {
  252. const root = await mkdtemp(join(tmpdir(), "zcode-design-default-"));
  253. try {
  254. const userConfigPath = join(root, "config.json");
  255. await writeFile(
  256. userConfigPath,
  257. JSON.stringify({
  258. plugins: {
  259. enabledPlugins:
  260. enabled === undefined ? {} : { "design@zcode-plugins-official": enabled },
  261. },
  262. }),
  263. );
  264. const outcome = await resolveZCodePlugins({
  265. env: {},
  266. pluginStorageRoot: join(root, "plugins"),
  267. userConfigPath,
  268. workingDirectory: root,
  269. });
  270. const design = outcome.plugins.find(
  271. (plugin) => plugin.id === "design@zcode-plugins-official",
  272. );
  273. expect(design).toBeDefined();
  274. expect(design?.enabled).toBe(enabled === true);
  275. expect(
  276. outcome.skillRoots.some(
  277. (skillRoot) => skillRoot.pluginId === "design@zcode-plugins-official",
  278. ),
  279. ).toBe(enabled === true);
  280. expect(
  281. outcome.hooks.SessionStart?.some((matcher) =>
  282. matcher.hooks.some((hook) => hook.plugin?.id === "design@zcode-plugins-official"),
  283. ) ?? false,
  284. ).toBe(enabled === true);
  285. } finally {
  286. await rm(root, { recursive: true, force: true });
  287. }
  288. },
  289. );
  290. it("can disable one document plugin without disabling the other formats or search", async () => {
  291. const root = await mkdtemp(join(tmpdir(), "zcode-document-toggle-"));
  292. try {
  293. const userConfigPath = join(root, "config.json");
  294. await writeFile(
  295. userConfigPath,
  296. JSON.stringify({
  297. plugins: { enabledPlugins: { "documents@zcode-plugins-official": false } },
  298. }),
  299. );
  300. const outcome = await resolveZCodePlugins({
  301. env: {},
  302. pluginStorageRoot: join(root, "plugins"),
  303. userConfigPath,
  304. workingDirectory: root,
  305. });
  306. expect(outcome.plugins.find((plugin) => plugin.name === "documents")?.enabled).toBe(false);
  307. for (const name of ["pdf", "presentations", "spreadsheets", "image-search"])
  308. expect(outcome.plugins.find((plugin) => plugin.name === name)?.enabled).toBe(true);
  309. } finally {
  310. await rm(root, { recursive: true, force: true });
  311. }
  312. });
  313. it("keeps same-name marketplace listings isolated by stable plugin id", async () => {
  314. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-plugin-listing-id-"));
  315. const pluginStorageRoot = join(root, "plugins");
  316. try {
  317. await writeKnownMarketplaces(pluginStorageRoot, [
  318. {
  319. id: "custom-marketplace",
  320. source: { source: "directory", path: root },
  321. name: "custom-marketplace",
  322. addedAt: "2026-08-23T00:00:00.000Z",
  323. pluginCount: 1,
  324. },
  325. ]);
  326. await writeTestFile(
  327. join(pluginStorageRoot, "marketplaces", "custom-marketplace", "marketplace.json"),
  328. JSON.stringify({
  329. name: "custom-marketplace",
  330. plugins: [
  331. {
  332. name: "computer-use",
  333. displayName: "Custom Computer Use",
  334. displayName_i18n: { "zh-CN": "自定义电脑控制" },
  335. },
  336. ],
  337. }),
  338. );
  339. const outcome = await listZCodePlugins({
  340. env: {},
  341. pluginStorageRoot,
  342. skipUserConfig: true,
  343. workingDirectory: root,
  344. });
  345. expect(outcome.pluginListingsById?.["computer-use@zcode-plugins-official"]).toMatchObject({
  346. displayName: "Computer Use",
  347. });
  348. expect(outcome.pluginListingsById?.["computer-use@custom-marketplace"]).toMatchObject({
  349. displayName: "Custom Computer Use",
  350. });
  351. } finally {
  352. await rm(root, { force: true, recursive: true });
  353. }
  354. });
  355. it("keeps the catalog and immutable cache for suppressed built-ins", async () => {
  356. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-suppressed-"));
  357. try {
  358. const pluginStorageRoot = join(root, "plugins");
  359. // First seed normally so the cache dir exists.
  360. await resolveOfficialPluginRoots({ storageRoot: pluginStorageRoot });
  361. const seededDir = join(pluginStorageRoot, OFFICIAL_SKILL_CREATOR_PLUGIN_CACHE_PATH);
  362. await stat(seededDir); // exists
  363. // Now suppress it and re-resolve.
  364. await resolveOfficialPluginRoots({
  365. storageRoot: pluginStorageRoot,
  366. suppressedBuiltins: new Set([SKILL_CREATOR_PLUGIN_ID]),
  367. });
  368. // 卸载只改变 Runtime 抑制态;Catalog 和不可变 cache 仍供详情页读取。
  369. await expect(stat(seededDir)).resolves.toBeDefined();
  370. // Synthetic marketplace.json 保留被抑制插件,避免详情请求变成 plugin_not_found。
  371. const manifest = JSON.parse(
  372. await readFile(
  373. join(pluginStorageRoot, "marketplaces", "zcode-plugins-official", "marketplace.json"),
  374. "utf8",
  375. ),
  376. );
  377. expect(
  378. manifest.plugins.find((p: { name: string }) => p.name === "skill-creator"),
  379. ).toMatchObject({
  380. source: "filesystem",
  381. });
  382. } finally {
  383. await rm(root, { force: true, recursive: true });
  384. }
  385. });
  386. it("marks update-available when a newer version exists in the manifest", async () => {
  387. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-update-detect-"));
  388. const pluginStorageRoot = join(root, "plugins");
  389. const marketplaceRoot = join(root, "marketplace");
  390. const pluginRoot = join(marketplaceRoot, "plugins", "demo");
  391. const configPath = join(root, "config.json");
  392. try {
  393. // Arrange a directory marketplace whose plugin declares v1, and install it so
  394. // installed_plugins.json records version 1.0.0.
  395. await writeKnownMarketplaces(pluginStorageRoot, [
  396. {
  397. id: "lazy-market",
  398. source: { source: "directory", path: marketplaceRoot },
  399. name: "lazy-market",
  400. addedAt: "2026-01-01T00:00:00.000Z",
  401. pluginCount: 0,
  402. },
  403. ]);
  404. await writeTestFile(
  405. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  406. JSON.stringify({
  407. name: "lazy-market",
  408. plugins: [{ name: "demo", source: "./plugins/demo", version: "1.0.0" }],
  409. }),
  410. );
  411. await writeTestFile(
  412. join(pluginRoot, ".claude-plugin", "plugin.json"),
  413. JSON.stringify({ name: "demo", skills: "skills", version: "1.0.0" }),
  414. );
  415. await writeTestFile(join(pluginRoot, "skills", "demo", "SKILL.md"), "# demo");
  416. await installZCodeMarketplacePlugin({
  417. marketplace: "lazy-market",
  418. pluginName: "demo",
  419. pluginStorageRoot,
  420. userConfigPath: configPath,
  421. workingDirectory: root,
  422. });
  423. // Now advertise a higher version (2.0.0) in the persisted marketplace manifest,
  424. // simulating an upstream release the installed copy hasn't caught up to.
  425. const manifestPath = join(
  426. pluginStorageRoot,
  427. "marketplaces",
  428. "lazy-market",
  429. "marketplace.json",
  430. );
  431. const manifest = JSON.parse(await readFile(manifestPath, "utf8")) as {
  432. name: string;
  433. plugins: Array<{ name: string; version?: string }>;
  434. };
  435. for (const entry of manifest.plugins) {
  436. if (entry.name === "demo") entry.version = "2.0.0";
  437. }
  438. await writeFile(manifestPath, JSON.stringify(manifest));
  439. const overview = await getZCodePluginsOverview({
  440. pluginStorageRoot,
  441. userConfigPath: configPath,
  442. workingDirectory: root,
  443. });
  444. const target = overview.installedPlugins.find((p) => p.id === "demo@lazy-market");
  445. expect(target?.updateStatus).toBe("update-available");
  446. expect(target?.latestVersion).toBe("2.0.0");
  447. } finally {
  448. await rm(root, { force: true, recursive: true });
  449. }
  450. });
  451. // The Claude-official shape: entries pin a commit sha (no top-level version). Detection must
  452. // compare installed record.source.sha vs manifest entry.source.sha, not entry.version.
  453. // (docs/plugin-marketplace-update-detection-handoff.md)
  454. it("marks update-available via source.sha when the manifest entry has no version", async () => {
  455. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-update-sha-"));
  456. const pluginStorageRoot = join(root, "plugins");
  457. const configPath = join(root, "config.json");
  458. try {
  459. await writeKnownMarketplaces(pluginStorageRoot, [
  460. {
  461. id: "sha-market",
  462. source: { source: "directory", path: join(root, "src") },
  463. name: "sha-market",
  464. addedAt: "2026-01-01T00:00:00.000Z",
  465. pluginCount: 1,
  466. },
  467. ]);
  468. // Persisted manifest pins a NEW sha, no version (mirrors a git-subdir official entry).
  469. await writeTestFile(
  470. join(pluginStorageRoot, "marketplaces", "sha-market", "marketplace.json"),
  471. JSON.stringify({
  472. name: "sha-market",
  473. plugins: [
  474. {
  475. name: "demo",
  476. source: {
  477. source: "git-subdir",
  478. url: "https://example.test/x.git",
  479. path: "p",
  480. sha: "newsha1234567890",
  481. },
  482. },
  483. ],
  484. }),
  485. );
  486. // Installed record snapshot carries the OLD sha.
  487. await writeTestFile(
  488. join(pluginStorageRoot, "installed_plugins.json"),
  489. JSON.stringify({
  490. plugins: [
  491. {
  492. id: "demo@sha-market",
  493. name: "demo",
  494. marketplace: "sha-market",
  495. version: "0.0.0",
  496. installPath: join(pluginStorageRoot, "cache", "sha-market", "demo", "0.0.0"),
  497. installedAt: "2026-01-01T00:00:00.000Z",
  498. scope: "user",
  499. source: {
  500. source: "git-subdir",
  501. url: "https://example.test/x.git",
  502. path: "p",
  503. sha: "oldsha0987654321",
  504. },
  505. },
  506. ],
  507. }),
  508. );
  509. const overview = await getZCodePluginsOverview({
  510. pluginStorageRoot,
  511. userConfigPath: configPath,
  512. workingDirectory: root,
  513. });
  514. const target = overview.installedPlugins.find((p) => p.id === "demo@sha-market");
  515. expect(target?.updateStatus).toBe("update-available");
  516. expect(target?.latestVersion).toBe("newsha1"); // short 7-char sha label
  517. } finally {
  518. await rm(root, { force: true, recursive: true });
  519. }
  520. });
  521. it("marks update-available via zip source sha256 when the manifest entry has no version", async () => {
  522. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-update-zip-sha-"));
  523. const pluginStorageRoot = join(root, "plugins");
  524. const configPath = join(root, "config.json");
  525. try {
  526. await writeKnownMarketplaces(pluginStorageRoot, [
  527. {
  528. id: "zip-market",
  529. source: { source: "directory", path: join(root, "src") },
  530. name: "zip-market",
  531. addedAt: "2026-01-01T00:00:00.000Z",
  532. pluginCount: 1,
  533. },
  534. ]);
  535. await writeTestFile(
  536. join(pluginStorageRoot, "marketplaces", "zip-market", "marketplace.json"),
  537. JSON.stringify({
  538. name: "zip-market",
  539. plugins: [
  540. {
  541. name: "demo",
  542. source: {
  543. source: "url",
  544. type: "zip",
  545. url: "https://cdn.example.test/demo.zip",
  546. sha256: `${"b".repeat(64)}`,
  547. },
  548. },
  549. ],
  550. }),
  551. );
  552. await writeTestFile(
  553. join(pluginStorageRoot, "installed_plugins.json"),
  554. JSON.stringify({
  555. plugins: [
  556. {
  557. id: "demo@zip-market",
  558. name: "demo",
  559. marketplace: "zip-market",
  560. version: "0.0.0",
  561. installPath: join(pluginStorageRoot, "cache", "zip-market", "demo", "0.0.0"),
  562. installedAt: "2026-01-01T00:00:00.000Z",
  563. scope: "user",
  564. source: {
  565. source: "url",
  566. type: "zip",
  567. url: "https://cdn.example.test/demo.zip",
  568. sha256: `${"a".repeat(64)}`,
  569. },
  570. },
  571. ],
  572. }),
  573. );
  574. const overview = await getZCodePluginsOverview({
  575. pluginStorageRoot,
  576. userConfigPath: configPath,
  577. workingDirectory: root,
  578. });
  579. const target = overview.installedPlugins.find((p) => p.id === "demo@zip-market");
  580. expect(target?.updateStatus).toBe("update-available");
  581. expect(target?.latestVersion).toBe("bbbbbbb");
  582. } finally {
  583. await rm(root, { force: true, recursive: true });
  584. }
  585. });
  586. it("lists suppressed official plugins as restorable built-ins", async () => {
  587. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-restorable-"));
  588. const pluginStorageRoot = join(root, "plugins");
  589. const userConfigPath = join(root, "config.json");
  590. try {
  591. await writeFile(
  592. userConfigPath,
  593. JSON.stringify({
  594. plugins: {
  595. enabled: true,
  596. suppressedBuiltins: [SKILL_CREATOR_PLUGIN_ID],
  597. },
  598. }),
  599. );
  600. const overview = await getZCodePluginsOverview({
  601. pluginStorageRoot,
  602. userConfigPath,
  603. workingDirectory: root,
  604. });
  605. expect(overview.restorableBuiltins.map((p) => p.id)).toContain(SKILL_CREATOR_PLUGIN_ID);
  606. } finally {
  607. await rm(root, { force: true, recursive: true });
  608. }
  609. });
  610. it("keeps the ui component type on a suppressed bundled document plugin", async () => {
  611. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-restorable-ui-"));
  612. const pluginStorageRoot = join(root, "plugins");
  613. const userConfigPath = join(root, "config.json");
  614. const documentsId = "documents@zcode-plugins-official";
  615. try {
  616. await writeFile(
  617. userConfigPath,
  618. JSON.stringify({ plugins: { enabled: true, suppressedBuiltins: [documentsId] } }),
  619. );
  620. const overview = await getZCodePluginsOverview({
  621. pluginStorageRoot,
  622. userConfigPath,
  623. workingDirectory: root,
  624. });
  625. // UI 合并时优先保留目录条目的 summary,所以目录条目与可恢复条目都必须带 "ui"。
  626. expect(
  627. overview.availablePlugins.find((plugin) => plugin.id === documentsId)?.componentTypes,
  628. ).toContain("ui");
  629. expect(
  630. overview.restorableBuiltins.find((plugin) => plugin.id === documentsId)?.componentTypes,
  631. ).toEqual(["ui"]);
  632. } finally {
  633. await rm(root, { force: true, recursive: true });
  634. }
  635. });
  636. it("includes the merged ZCode official marketplace and Claude marketplace for empty storage", async () => {
  637. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-default-marketplace-"));
  638. try {
  639. const pluginStorageRoot = join(root, "plugins");
  640. const overview = await getZCodePluginsOverview({
  641. env: {},
  642. pluginStorageRoot,
  643. skipUserConfig: true,
  644. workingDirectory: root,
  645. });
  646. expect(overview.marketplaces).toEqual(
  647. expect.arrayContaining([
  648. expect.objectContaining({
  649. id: "zcode-plugins-official",
  650. isOfficial: true,
  651. name: "zcode-plugins-official",
  652. pluginCount: 16,
  653. source: {
  654. source: "url",
  655. url: "https://cdn-zcode.z.ai/zcode/official-plugin/marketplace.json",
  656. },
  657. }),
  658. expect.objectContaining({
  659. id: "claude-plugins-official",
  660. isOfficial: true,
  661. name: "claude-plugins-official",
  662. pluginCount: 0,
  663. source: {
  664. repo: "anthropics/claude-plugins-official",
  665. source: "github",
  666. },
  667. }),
  668. ]),
  669. );
  670. expect(
  671. JSON.parse(await readFile(join(pluginStorageRoot, "known_marketplaces.json"), "utf8")),
  672. ).toMatchObject({
  673. marketplaces: [
  674. expect.objectContaining({
  675. id: "zcode-plugins-official",
  676. }),
  677. expect.objectContaining({
  678. id: "claude-plugins-official",
  679. }),
  680. ],
  681. });
  682. } finally {
  683. await rm(root, { force: true, recursive: true });
  684. }
  685. });
  686. it("installs from a known marketplace by lazy-loading its missing manifest", async () => {
  687. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-lazy-marketplace-install-"));
  688. const pluginStorageRoot = join(root, "plugins");
  689. const marketplaceRoot = join(root, "marketplace");
  690. const pluginRoot = join(marketplaceRoot, "plugins", "hello");
  691. try {
  692. await writeKnownMarketplaces(pluginStorageRoot, [
  693. {
  694. id: "lazy-market",
  695. source: { source: "directory", path: marketplaceRoot },
  696. name: "lazy-market",
  697. addedAt: "2026-01-01T00:00:00.000Z",
  698. pluginCount: 0,
  699. },
  700. ]);
  701. await writeTestFile(
  702. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  703. JSON.stringify({
  704. name: "lazy-market",
  705. plugins: [
  706. {
  707. name: "hello",
  708. source: "./plugins/hello",
  709. componentTypes: ["ui"],
  710. publisherType: "community",
  711. },
  712. ],
  713. }),
  714. );
  715. await writeTestFile(
  716. join(pluginRoot, ".claude-plugin", "plugin.json"),
  717. JSON.stringify({
  718. name: "hello",
  719. skills: "skills",
  720. mcpServers: { panel: { command: "node", args: ["panel.mjs"] } },
  721. ui: {
  722. surfaces: [
  723. {
  724. id: "panel",
  725. title: "Panel",
  726. server: "panel",
  727. resourceUri: "ui://hello/panel",
  728. availability: "session",
  729. },
  730. ],
  731. },
  732. }),
  733. );
  734. await writeTestFile(join(pluginRoot, "skills", "hello", "SKILL.md"), "# hello");
  735. await writeTestFile(join(pluginRoot, "agents", "judge.md"), "---\nname: judge\n---\n");
  736. const configPath = join(root, "config.json");
  737. const result = await installZCodeMarketplacePlugin({
  738. marketplace: "lazy-market",
  739. pluginName: "hello",
  740. pluginStorageRoot,
  741. userConfigPath: configPath,
  742. workingDirectory: root,
  743. });
  744. expect(result.diagnostics).toEqual([]);
  745. expect(result.dependencyClosure).toEqual(["hello@lazy-market"]);
  746. expect(result.installedPlugins[0]).toMatchObject({
  747. id: "hello@lazy-market",
  748. marketplace: "lazy-market",
  749. // 安装即默认启用:新装插件应直接 enabled,无需再手动开。
  750. enabled: true,
  751. });
  752. const overview = await getZCodePluginsOverview({
  753. pluginStorageRoot,
  754. userConfigPath: configPath,
  755. workingDirectory: root,
  756. });
  757. expect(overview.installedPlugins[0]?.componentTypes).toEqual(
  758. expect.arrayContaining(["agent", "skill", "mcp", "ui"]),
  759. );
  760. expect(
  761. overview.availablePlugins.find((plugin) => plugin.id === "hello@lazy-market"),
  762. ).toMatchObject({ componentTypes: ["ui"], listing: { publisherType: "community" } });
  763. await expect(
  764. readFile(
  765. join(pluginStorageRoot, "marketplaces", "lazy-market", "marketplace.json"),
  766. "utf8",
  767. ),
  768. ).resolves.toContain("lazy-market");
  769. // 默认启用应落到用户配置 enabledPlugins。
  770. const persisted = JSON.parse(await readFile(configPath, "utf8")) as {
  771. plugins?: { enabledPlugins?: Record<string, boolean> };
  772. };
  773. expect(persisted.plugins?.enabledPlugins?.["hello@lazy-market"]).toBe(true);
  774. } finally {
  775. await rm(root, { force: true, recursive: true });
  776. }
  777. });
  778. it("两个独立 CLI 同时安装到同一个 Host 时,缓存、安装记录和默认启用项均保留", async () => {
  779. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-processes-"));
  780. const pluginStorageRoot = join(root, "plugins");
  781. const userConfigPath = join(root, "config.json");
  782. const names = ["first", "second"];
  783. const archives = names.map((name) =>
  784. createStoredZip([
  785. {
  786. path: `${name}/.zcode-plugin/plugin.json`,
  787. content: JSON.stringify({ name, version: "1.0.0" }),
  788. },
  789. ]),
  790. );
  791. const firstDownload = Promise.withResolvers<void>();
  792. const release = Promise.withResolvers<void>();
  793. const server = createServer(async (req, res) => {
  794. const index = req.url === "/first.zip" ? 0 : 1;
  795. if (index === 0) {
  796. firstDownload.resolve();
  797. await release.promise;
  798. }
  799. res.end(archives[index]);
  800. });
  801. const workers: Promise<unknown>[] = [];
  802. try {
  803. await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
  804. const address = server.address();
  805. if (!address || typeof address === "string") throw new Error("missing fixture port");
  806. await writeTestFile(
  807. join(pluginStorageRoot, "marketplaces", "fixture", "marketplace.json"),
  808. JSON.stringify({
  809. name: "fixture",
  810. plugins: names.map((name, i) => ({
  811. name,
  812. source: {
  813. source: "url",
  814. type: "zip",
  815. url: `http://127.0.0.1:${address.port}/${name}.zip`,
  816. sha256: hashBytes(archives[i]!),
  817. },
  818. })),
  819. }),
  820. );
  821. await Promise.all(names.map((name) => mkdir(join(root, name))));
  822. const install = (name: string) => {
  823. const run = promisify(execFile)(process.execPath, [
  824. "--import",
  825. "tsx",
  826. "--input-type=module",
  827. "-e",
  828. `const { installZCodeMarketplacePlugin } = await import(process.argv[1]);
  829. const options = JSON.parse(process.argv[2]);
  830. process.stdout.write("ready\\n");
  831. const result = await installZCodeMarketplacePlugin(options);
  832. if (result.installedPlugins.length !== 1) throw new Error(JSON.stringify(result));`,
  833. new URL("../src/plugins.ts", import.meta.url).href,
  834. JSON.stringify({
  835. pluginName: name,
  836. marketplace: "fixture",
  837. pluginStorageRoot,
  838. userConfigPath,
  839. workingDirectory: join(root, name),
  840. }),
  841. ]);
  842. workers.push(run);
  843. return run;
  844. };
  845. const first = install("first");
  846. await Promise.race([
  847. firstDownload.promise,
  848. first.then(() => {
  849. throw new Error("first installation did not fetch the archive");
  850. }),
  851. ]);
  852. const second = install("second");
  853. const ready = new Promise<void>((done) => second.child.stdout!.once("data", () => done()));
  854. await Promise.race([ready, second]);
  855. // 第一个 writer 已读库存;给第二个真实进程机会完成安装,再放行第一个下载。
  856. await Promise.race([second, delay(500)]);
  857. release.resolve();
  858. await Promise.all(workers);
  859. const state = JSON.parse(
  860. await readFile(join(pluginStorageRoot, "installed_plugins.json"), "utf8"),
  861. );
  862. expect(state.plugins.map((p: { id: string }) => p.id).sort()).toEqual(
  863. names.map((n) => `${n}@fixture`),
  864. );
  865. for (const record of state.plugins) {
  866. expect(
  867. JSON.parse(
  868. await readFile(join(record.installPath, ".zcode-plugin", "plugin.json"), "utf8"),
  869. ).name,
  870. ).toBe(record.name);
  871. }
  872. expect(JSON.parse(await readFile(userConfigPath, "utf8")).plugins.enabledPlugins).toEqual({
  873. "first@fixture": true,
  874. "second@fixture": true,
  875. });
  876. } finally {
  877. release.resolve();
  878. await Promise.allSettled(workers);
  879. await closeServer(server);
  880. await rm(root, { recursive: true, force: true });
  881. }
  882. }, 30_000);
  883. it("installs and enables a marketplace plugin from a zip URL source through the facade", async () => {
  884. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-zip-marketplace-install-"));
  885. const pluginStorageRoot = join(root, "plugins");
  886. const marketplaceRoot = join(root, "marketplace");
  887. const configPath = join(root, "config.json");
  888. let server: Server | undefined;
  889. try {
  890. const zipBuffer = createStoredZip([
  891. {
  892. path: "hello-zip/.claude-plugin/plugin.json",
  893. content: JSON.stringify({
  894. name: "hello-zip",
  895. skills: "skills",
  896. version: "4.5.6",
  897. }),
  898. },
  899. {
  900. path: "hello-zip/skills/hello/SKILL.md",
  901. content: "# hello zip\n",
  902. },
  903. {
  904. path: "hello-zip/agents/judge.md",
  905. content: "---\nname: judge\n---\n",
  906. },
  907. ]);
  908. const fixture = await startZipFixtureServer({
  909. "/hello-zip.zip": zipBuffer,
  910. });
  911. server = fixture.server;
  912. await writeKnownMarketplaces(pluginStorageRoot, [
  913. {
  914. id: "zip-lazy-market",
  915. source: { source: "directory", path: marketplaceRoot },
  916. name: "zip-lazy-market",
  917. addedAt: "2026-01-01T00:00:00.000Z",
  918. pluginCount: 0,
  919. },
  920. ]);
  921. await writeTestFile(
  922. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  923. JSON.stringify({
  924. name: "zip-lazy-market",
  925. plugins: [
  926. {
  927. name: "hello-zip",
  928. source: {
  929. source: "url",
  930. type: "zip",
  931. url: `${fixture.baseUrl}/hello-zip.zip`,
  932. sha256: hashBytes(zipBuffer),
  933. },
  934. },
  935. ],
  936. }),
  937. );
  938. const result = await installZCodeMarketplacePlugin({
  939. marketplace: "zip-lazy-market",
  940. pluginName: "hello-zip",
  941. pluginStorageRoot,
  942. userConfigPath: configPath,
  943. workingDirectory: root,
  944. });
  945. expect(result.diagnostics).toEqual([]);
  946. expect(result.dependencyClosure).toEqual(["hello-zip@zip-lazy-market"]);
  947. expect(result.installedPlugins[0]).toMatchObject({
  948. enabled: true,
  949. id: "hello-zip@zip-lazy-market",
  950. marketplace: "zip-lazy-market",
  951. version: "4.5.6",
  952. });
  953. expect(result.installedPlugins[0]?.installPath).toContain(
  954. join("cache", "zip-lazy-market", "hello-zip", "4.5.6"),
  955. );
  956. expect(
  957. existsSync(join(result.installedPlugins[0]?.installPath ?? "", "agents", "judge.md")),
  958. ).toBe(true);
  959. const overviewResult = await getZCodePluginsOverview({
  960. pluginStorageRoot,
  961. userConfigPath: configPath,
  962. workingDirectory: root,
  963. });
  964. expect(
  965. overviewResult.installedPlugins.find((item) => item.id === "hello-zip@zip-lazy-market"),
  966. ).toMatchObject({
  967. componentTypes: expect.arrayContaining(["agent", "skill"]),
  968. enabled: true,
  969. version: "4.5.6",
  970. });
  971. } finally {
  972. await closeServer(server);
  973. await rm(root, { force: true, recursive: true });
  974. }
  975. });
  976. it.each(["user", "workspace"] as const)(
  977. "preserves an explicit %s disable when installing a plugin",
  978. async (scope) => {
  979. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-reinstall-disabled-"));
  980. const pluginStorageRoot = join(root, "plugins");
  981. const marketplaceRoot = join(root, "marketplace");
  982. const pluginRoot = join(marketplaceRoot, "plugins", "hello");
  983. const configPath = join(root, "config.json");
  984. try {
  985. await writeKnownMarketplaces(pluginStorageRoot, [
  986. {
  987. id: "lazy-market",
  988. source: { source: "directory", path: marketplaceRoot },
  989. name: "lazy-market",
  990. addedAt: "2026-01-01T00:00:00.000Z",
  991. pluginCount: 0,
  992. },
  993. ]);
  994. await writeTestFile(
  995. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  996. JSON.stringify({
  997. name: "lazy-market",
  998. plugins: [{ name: "hello", source: "./plugins/hello" }],
  999. }),
  1000. );
  1001. await writeTestFile(
  1002. join(pluginRoot, ".claude-plugin", "plugin.json"),
  1003. JSON.stringify({ name: "hello", skills: "skills" }),
  1004. );
  1005. await writeTestFile(join(pluginRoot, "skills", "hello", "SKILL.md"), "# hello");
  1006. // User 安装不能覆盖 User 或 Workspace 已有的禁用选择。
  1007. const projectConfigPath = join(root, ".zcode", "config.json");
  1008. const overridePath = scope === "user" ? configPath : projectConfigPath;
  1009. await writeTestFile(
  1010. overridePath,
  1011. JSON.stringify({
  1012. plugins: { enabledPlugins: { "hello@lazy-market": false } },
  1013. }),
  1014. );
  1015. const result = await installZCodeMarketplacePlugin({
  1016. marketplace: "lazy-market",
  1017. pluginName: "hello",
  1018. pluginStorageRoot,
  1019. userConfigPath: configPath,
  1020. workingDirectory: root,
  1021. });
  1022. expect(result.installedPlugins[0]?.id).toBe("hello@lazy-market");
  1023. if (scope === "user") expect(result.installedPlugins[0]?.enabled).toBe(false);
  1024. const { plugins } = await resolveZCodePlugins({
  1025. pluginStorageRoot,
  1026. projectConfigPath,
  1027. userConfigPath: configPath,
  1028. workingDirectory: root,
  1029. });
  1030. expect(plugins.find((plugin) => plugin.id === "hello@lazy-market")?.enabled).toBe(false);
  1031. const persisted = JSON.parse(await readFile(overridePath, "utf8")) as {
  1032. plugins?: { enabledPlugins?: Record<string, boolean> };
  1033. };
  1034. expect(persisted.plugins?.enabledPlugins?.["hello@lazy-market"]).toBe(false);
  1035. } finally {
  1036. await rm(root, { force: true, recursive: true });
  1037. }
  1038. },
  1039. );
  1040. it("thoroughly uninstalls a plugin and prunes its user config footprint", async () => {
  1041. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-uninstall-"));
  1042. const pluginStorageRoot = join(root, "plugins");
  1043. const marketplaceRoot = join(root, "marketplace");
  1044. const pluginRoot = join(marketplaceRoot, "plugins", "hello");
  1045. const configPath = join(root, "config.json");
  1046. try {
  1047. await writeKnownMarketplaces(pluginStorageRoot, [
  1048. {
  1049. id: "lazy-market",
  1050. source: { source: "directory", path: marketplaceRoot },
  1051. name: "lazy-market",
  1052. addedAt: "2026-01-01T00:00:00.000Z",
  1053. pluginCount: 0,
  1054. },
  1055. ]);
  1056. await writeTestFile(
  1057. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  1058. JSON.stringify({
  1059. name: "lazy-market",
  1060. plugins: [{ name: "hello", source: "./plugins/hello" }],
  1061. }),
  1062. );
  1063. await writeTestFile(
  1064. join(pluginRoot, ".claude-plugin", "plugin.json"),
  1065. JSON.stringify({ name: "hello", skills: "skills" }),
  1066. );
  1067. await writeTestFile(join(pluginRoot, "skills", "hello", "SKILL.md"), "# hello");
  1068. const installed = await installZCodeMarketplacePlugin({
  1069. marketplace: "lazy-market",
  1070. pluginName: "hello",
  1071. pluginStorageRoot,
  1072. userConfigPath: configPath,
  1073. workingDirectory: root,
  1074. });
  1075. const installPath = installed.installedPlugins[0]?.installPath ?? "";
  1076. expect(existsSync(installPath)).toBe(true);
  1077. // 预置 user config 里的启用标记/选项与运行期 data 目录,验证卸载会一并清掉。
  1078. await writeTestFile(
  1079. configPath,
  1080. JSON.stringify({
  1081. plugins: {
  1082. enabledPlugins: {
  1083. "hello@lazy-market": true,
  1084. "keep@lazy-market": true,
  1085. },
  1086. options: { "hello@lazy-market": { foo: "bar" } },
  1087. },
  1088. }),
  1089. );
  1090. const dataDir = join(pluginStorageRoot, "data", "hello@lazy-market");
  1091. await mkdir(dataDir, { recursive: true });
  1092. await writeTestFile(join(dataDir, "generated-commands", "demo.md"), "# demo");
  1093. const removed = await uninstallZCodeMarketplacePlugin({
  1094. pluginId: "hello@lazy-market",
  1095. pluginStorageRoot,
  1096. userConfigPath: configPath,
  1097. skipUserConfig: false,
  1098. workingDirectory: root,
  1099. });
  1100. expect(removed?.id).toBe("hello@lazy-market");
  1101. expect(existsSync(installPath)).toBe(false);
  1102. expect(existsSync(dataDir)).toBe(false);
  1103. const parsed = JSON.parse(await readFile(configPath, "utf8")) as {
  1104. plugins: {
  1105. enabledPlugins: Record<string, boolean>;
  1106. options: Record<string, unknown>;
  1107. };
  1108. };
  1109. expect(parsed.plugins.enabledPlugins).toEqual({
  1110. "keep@lazy-market": true,
  1111. });
  1112. expect(parsed.plugins.options).toEqual({});
  1113. } finally {
  1114. await rm(root, { force: true, recursive: true });
  1115. }
  1116. });
  1117. it("treats an installed official-CDN cache entry as marketplace-owned during uninstall", async () => {
  1118. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-uninstall-official-cdn-"));
  1119. const pluginStorageRoot = join(root, "plugins");
  1120. const userConfigPath = join(root, "config.json");
  1121. const pluginId = "example-plugin@zcode-plugins-official";
  1122. const installPath = join(
  1123. pluginStorageRoot,
  1124. "cache",
  1125. "zcode-plugins-official",
  1126. "example-plugin",
  1127. "0.2.0",
  1128. );
  1129. try {
  1130. await writeTestFile(
  1131. join(installPath, ".zcode-plugin", "plugin.json"),
  1132. JSON.stringify({
  1133. name: "example-plugin",
  1134. version: "0.2.0",
  1135. skills: "skills",
  1136. }),
  1137. );
  1138. await writeTestFile(join(installPath, "skills", "example", "SKILL.md"), "# example");
  1139. await writeTestFile(
  1140. join(pluginStorageRoot, "installed_plugins.json"),
  1141. JSON.stringify({
  1142. version: 1,
  1143. plugins: [
  1144. {
  1145. id: pluginId,
  1146. name: "example-plugin",
  1147. marketplace: "zcode-plugins-official",
  1148. version: "0.2.0",
  1149. installPath,
  1150. installedAt: "2026-07-15T00:00:00.000Z",
  1151. updatedAt: "2026-07-15T00:00:00.000Z",
  1152. scope: "user",
  1153. },
  1154. ],
  1155. }),
  1156. );
  1157. await writeTestFile(
  1158. userConfigPath,
  1159. JSON.stringify({
  1160. plugins: {
  1161. enabledPlugins: { [pluginId]: true },
  1162. options: { [pluginId]: { foo: "bar" } },
  1163. },
  1164. }),
  1165. );
  1166. const removed = await uninstallZCodeMarketplacePlugin({
  1167. pluginId,
  1168. pluginStorageRoot,
  1169. userConfigPath,
  1170. workingDirectory: root,
  1171. });
  1172. expect(removed?.id).toBe(pluginId);
  1173. expect(existsSync(installPath)).toBe(false);
  1174. const installedState = JSON.parse(
  1175. await readFile(join(pluginStorageRoot, "installed_plugins.json"), "utf8"),
  1176. );
  1177. expect(installedState.plugins).toEqual([]);
  1178. const config = JSON.parse(await readFile(userConfigPath, "utf8"));
  1179. expect(config.plugins.suppressedBuiltins ?? []).not.toContain(pluginId);
  1180. expect(config.plugins.enabledPlugins?.[pluginId]).toBeUndefined();
  1181. expect(config.plugins.options?.[pluginId]).toBeUndefined();
  1182. } finally {
  1183. await rm(root, { force: true, recursive: true });
  1184. }
  1185. });
  1186. it("clears stale built-in suppression while removing an installed marketplace record", async () => {
  1187. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-uninstall-stale-suppression-"));
  1188. const pluginStorageRoot = join(root, "plugins");
  1189. const userConfigPath = join(root, "config.json");
  1190. const pluginId = "example-plugin@zcode-plugins-official";
  1191. const installPath = join(
  1192. pluginStorageRoot,
  1193. "cache",
  1194. "zcode-plugins-official",
  1195. "example-plugin",
  1196. "0.2.0",
  1197. );
  1198. try {
  1199. await writeTestFile(
  1200. join(installPath, ".zcode-plugin", "plugin.json"),
  1201. JSON.stringify({ name: "example-plugin", version: "0.2.0" }),
  1202. );
  1203. await writeTestFile(
  1204. join(pluginStorageRoot, "installed_plugins.json"),
  1205. JSON.stringify({
  1206. version: 1,
  1207. plugins: [
  1208. {
  1209. id: pluginId,
  1210. name: "example-plugin",
  1211. marketplace: "zcode-plugins-official",
  1212. version: "0.2.0",
  1213. installPath,
  1214. installedAt: "2026-07-15T00:00:00.000Z",
  1215. updatedAt: "2026-07-15T00:00:00.000Z",
  1216. scope: "user",
  1217. },
  1218. ],
  1219. }),
  1220. );
  1221. await writeTestFile(
  1222. userConfigPath,
  1223. JSON.stringify({ plugins: { suppressedBuiltins: [pluginId] } }),
  1224. );
  1225. await uninstallZCodeMarketplacePlugin({
  1226. pluginId,
  1227. pluginStorageRoot,
  1228. userConfigPath,
  1229. workingDirectory: root,
  1230. });
  1231. const config = JSON.parse(await readFile(userConfigPath, "utf8"));
  1232. expect(config.plugins.suppressedBuiltins ?? []).not.toContain(pluginId);
  1233. const installedState = JSON.parse(
  1234. await readFile(join(pluginStorageRoot, "installed_plugins.json"), "utf8"),
  1235. );
  1236. expect(installedState.plugins).toEqual([]);
  1237. } finally {
  1238. await rm(root, { force: true, recursive: true });
  1239. }
  1240. });
  1241. it("uninstalls a built-in by suppressing it and purging config", async () => {
  1242. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-uninstall-builtin-"));
  1243. const pluginStorageRoot = join(root, "plugins");
  1244. const userConfigPath = join(root, "config.json");
  1245. try {
  1246. await writeFile(
  1247. userConfigPath,
  1248. JSON.stringify({
  1249. plugins: {
  1250. enabled: true,
  1251. enabledPlugins: { [SKILL_CREATOR_PLUGIN_ID]: true },
  1252. options: { [SKILL_CREATOR_PLUGIN_ID]: { foo: "bar" } },
  1253. },
  1254. }),
  1255. );
  1256. // Seed first so its cache exists.
  1257. await resolveZCodePlugins({
  1258. pluginStorageRoot,
  1259. userConfigPath,
  1260. workingDirectory: root,
  1261. });
  1262. const cacheDir = join(pluginStorageRoot, OFFICIAL_SKILL_CREATOR_PLUGIN_CACHE_PATH);
  1263. await stat(cacheDir);
  1264. const removed = await uninstallZCodeMarketplacePlugin({
  1265. pluginId: SKILL_CREATOR_PLUGIN_ID,
  1266. pluginStorageRoot,
  1267. userConfigPath,
  1268. workingDirectory: root,
  1269. });
  1270. expect(removed?.id).toBe(SKILL_CREATOR_PLUGIN_ID);
  1271. const config = JSON.parse(await readFile(userConfigPath, "utf8"));
  1272. expect(config.plugins.suppressedBuiltins).toContain(SKILL_CREATOR_PLUGIN_ID);
  1273. expect(config.plugins.enabledPlugins?.[SKILL_CREATOR_PLUGIN_ID]).toBeUndefined();
  1274. expect(config.plugins.options?.[SKILL_CREATOR_PLUGIN_ID]).toBeUndefined();
  1275. // Re-resolve: Runtime stays gone, but Catalog/cache remain readable for detail/restore.
  1276. const outcome = await resolveZCodePlugins({
  1277. pluginStorageRoot,
  1278. userConfigPath,
  1279. workingDirectory: root,
  1280. });
  1281. expect(outcome.plugins.find((p) => p.id === SKILL_CREATOR_PLUGIN_ID)).toBeUndefined();
  1282. await expect(stat(cacheDir)).resolves.toBeDefined();
  1283. const detail = await describeZCodePlugin({
  1284. pluginName: "skill-creator",
  1285. marketplace: "zcode-plugins-official",
  1286. pluginStorageRoot,
  1287. userConfigPath,
  1288. workingDirectory: root,
  1289. });
  1290. expect(detail.diagnostics.filter((diagnostic) => diagnostic.severity === "error")).toEqual(
  1291. [],
  1292. );
  1293. expect(detail.components.length).toBeGreaterThan(0);
  1294. // Double-uninstall is idempotent: an already-suppressed built-in is not resolved,
  1295. // so it falls through to the marketplace path and returns null without throwing.
  1296. const second = await uninstallZCodeMarketplacePlugin({
  1297. pluginId: SKILL_CREATOR_PLUGIN_ID,
  1298. pluginStorageRoot,
  1299. userConfigPath,
  1300. workingDirectory: root,
  1301. });
  1302. expect(second).toBeNull();
  1303. } finally {
  1304. await rm(root, { force: true, recursive: true });
  1305. }
  1306. });
  1307. // Finding #3: the in-session plugin facade caches config at construction time. Before the
  1308. // fix it only refreshed enabledPlugins on uninstall, keeping the startup-time
  1309. // suppressedBuiltins, so a built-in uninstalled via the facade re-appeared on the next
  1310. // listPlugins() in the SAME process. The facade must also track suppressedBuiltins.
  1311. it("keeps a built-in uninstalled within the same facade session", async () => {
  1312. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-facade-uninstall-"));
  1313. const pluginStorageRoot = join(root, "plugins");
  1314. const userConfigPath = join(root, "config.json");
  1315. try {
  1316. await writeFile(userConfigPath, JSON.stringify({ plugins: { enabled: true } }));
  1317. const configResult = createConfig({
  1318. env: {},
  1319. userConfigPath,
  1320. workingDirectory: root,
  1321. });
  1322. const facade = createPluginFacadeForApp({
  1323. configResult,
  1324. options: { env: {}, pluginStorageRoot } as ZCodeAppOptions,
  1325. workingDirectory: root,
  1326. });
  1327. const before = await facade.listPlugins();
  1328. expect(before.plugins.find((item) => item.id === SKILL_CREATOR_PLUGIN_ID)).toBeDefined();
  1329. const { removed } = await facade.uninstallPlugin(SKILL_CREATOR_PLUGIN_ID);
  1330. expect(removed?.id).toBe(SKILL_CREATOR_PLUGIN_ID);
  1331. // Same facade instance, subsequent list must not re-surface the uninstalled built-in.
  1332. const after = await facade.listPlugins();
  1333. expect(after.plugins.find((item) => item.id === SKILL_CREATOR_PLUGIN_ID)).toBeUndefined();
  1334. } finally {
  1335. await rm(root, { force: true, recursive: true });
  1336. }
  1337. });
  1338. it.each(["restore", "install", "prepare-failed"] as const)(
  1339. "keeps suppression unchanged when %s cannot prepare plugins",
  1340. async (entry) => {
  1341. const root = await mkdtemp(join(tmpdir(), "zcode-degraded-restore-"));
  1342. const userConfigPath = join(root, "config.json");
  1343. const before = JSON.stringify({
  1344. plugins: { enabled: true, suppressedBuiltins: [SKILL_CREATOR_PLUGIN_ID] },
  1345. });
  1346. const pluginPreparation = createOfficialPluginPreparation(
  1347. entry === "prepare-failed" ? undefined : { startupTimeoutMs: 0 },
  1348. );
  1349. try {
  1350. if (entry === "prepare-failed")
  1351. vi.spyOn(pluginPreparation, "prepare").mockRejectedValue(
  1352. Object.assign(new Error("Plugin startup timed out"), {
  1353. code: "ZCODE_PLUGIN_STARTUP_TIMEOUT",
  1354. }),
  1355. );
  1356. else await pluginPreparation.resolvePlugins(() => new Promise(() => {}));
  1357. await writeFile(userConfigPath, before);
  1358. const options = {
  1359. pluginPreparation,
  1360. pluginStorageRoot: join(root, "plugins"),
  1361. userConfigPath,
  1362. workingDirectory: root,
  1363. };
  1364. const catalog = join(options.pluginStorageRoot, "marketplaces", "zcode-plugins-official");
  1365. await mkdir(catalog, { recursive: true });
  1366. await writeFile(
  1367. join(catalog, "marketplace.json"),
  1368. JSON.stringify({
  1369. name: "zcode-plugins-official",
  1370. plugins: [{ name: "skill-creator", source: "filesystem" }],
  1371. }),
  1372. );
  1373. const restore =
  1374. entry !== "install"
  1375. ? restoreBuiltinPlugin({ ...options, pluginId: SKILL_CREATOR_PLUGIN_ID })
  1376. : installZCodeMarketplacePlugin({
  1377. ...options,
  1378. marketplace: "zcode-plugins-official",
  1379. pluginName: "skill-creator",
  1380. });
  1381. await expect(restore).rejects.toMatchObject({ code: "ZCODE_PLUGIN_STARTUP_TIMEOUT" });
  1382. expect(await readFile(userConfigPath, "utf8")).toBe(before);
  1383. expect(existsSync(join(options.pluginStorageRoot, "installed_plugins.json"))).toBe(false);
  1384. } finally {
  1385. await pluginPreparation.dispose();
  1386. await rm(root, { recursive: true, force: true });
  1387. }
  1388. },
  1389. );
  1390. it("restores a suppressed built-in so it re-seeds on next resolve", async () => {
  1391. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-restore-builtin-"));
  1392. const pluginStorageRoot = join(root, "plugins");
  1393. const userConfigPath = join(root, "config.json");
  1394. try {
  1395. await writeFile(
  1396. userConfigPath,
  1397. JSON.stringify({
  1398. plugins: {
  1399. enabled: true,
  1400. suppressedBuiltins: [SKILL_CREATOR_PLUGIN_ID],
  1401. },
  1402. }),
  1403. );
  1404. // Suppressed: not present.
  1405. let outcome = await resolveZCodePlugins({
  1406. pluginStorageRoot,
  1407. userConfigPath,
  1408. workingDirectory: root,
  1409. });
  1410. expect(outcome.plugins.find((p) => p.id === SKILL_CREATOR_PLUGIN_ID)).toBeUndefined();
  1411. await restoreBuiltinPlugin({
  1412. pluginId: SKILL_CREATOR_PLUGIN_ID,
  1413. pluginStorageRoot,
  1414. userConfigPath,
  1415. workingDirectory: root,
  1416. });
  1417. const config = JSON.parse(await readFile(userConfigPath, "utf8"));
  1418. expect(config.plugins.suppressedBuiltins ?? []).not.toContain(SKILL_CREATOR_PLUGIN_ID);
  1419. outcome = await resolveZCodePlugins({
  1420. pluginStorageRoot,
  1421. userConfigPath,
  1422. workingDirectory: root,
  1423. });
  1424. expect(outcome.plugins.find((p) => p.id === SKILL_CREATOR_PLUGIN_ID)).toBeDefined();
  1425. } finally {
  1426. await rm(root, { force: true, recursive: true });
  1427. }
  1428. });
  1429. it("routes a direct install of a suppressed bundled plugin to restore without creating a marketplace record", async () => {
  1430. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-install-bundled-restore-"));
  1431. const pluginStorageRoot = join(root, "plugins");
  1432. const userConfigPath = join(root, "config.json");
  1433. try {
  1434. await writeFile(
  1435. userConfigPath,
  1436. JSON.stringify({
  1437. plugins: {
  1438. enabled: true,
  1439. suppressedBuiltins: [SKILL_CREATOR_PLUGIN_ID],
  1440. },
  1441. }),
  1442. );
  1443. // 先写入完整 Catalog/cache,模拟详情页仍可见但 Runtime 被抑制的状态。
  1444. await resolveZCodePlugins({
  1445. pluginStorageRoot,
  1446. userConfigPath,
  1447. workingDirectory: root,
  1448. });
  1449. const result = await installZCodeMarketplacePlugin({
  1450. marketplace: "zcode-plugins-official",
  1451. pluginName: "skill-creator",
  1452. pluginStorageRoot,
  1453. userConfigPath,
  1454. workingDirectory: root,
  1455. });
  1456. expect(result.diagnostics).toEqual([]);
  1457. expect(result.installedPlugins.map((plugin) => plugin.id)).toEqual([SKILL_CREATOR_PLUGIN_ID]);
  1458. expect(existsSync(join(pluginStorageRoot, "installed_plugins.json"))).toBe(false);
  1459. expect(JSON.parse(await readFile(userConfigPath, "utf8"))).not.toMatchObject({
  1460. plugins: { suppressedBuiltins: [SKILL_CREATOR_PLUGIN_ID] },
  1461. });
  1462. } finally {
  1463. await rm(root, { force: true, recursive: true });
  1464. }
  1465. });
  1466. it("clears stale builtin suppression when an official CDN entry with the same id is installed", async () => {
  1467. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-cdn-suppression-"));
  1468. const pluginStorageRoot = join(root, "plugins");
  1469. const userConfigPath = join(root, "config.json");
  1470. const cdnSourceRoot = join(root, "cdn-documents");
  1471. try {
  1472. await writeFile(
  1473. userConfigPath,
  1474. JSON.stringify({
  1475. plugins: {
  1476. enabled: true,
  1477. suppressedBuiltins: [DOCUMENTS_PLUGIN_ID],
  1478. },
  1479. }),
  1480. );
  1481. await mkdir(join(cdnSourceRoot, ".zcode-plugin"), { recursive: true });
  1482. await writeFile(
  1483. join(cdnSourceRoot, ".zcode-plugin", "plugin.json"),
  1484. JSON.stringify({
  1485. name: "documents",
  1486. version: "1.0.0",
  1487. skills: "skills",
  1488. }),
  1489. );
  1490. await mkdir(join(cdnSourceRoot, "skills", "documents"), {
  1491. recursive: true,
  1492. });
  1493. await writeFile(
  1494. join(cdnSourceRoot, "skills", "documents", "SKILL.md"),
  1495. "# Document Skills\n",
  1496. );
  1497. await resolveZCodePlugins({
  1498. pluginStorageRoot,
  1499. userConfigPath,
  1500. workingDirectory: root,
  1501. });
  1502. const manifestPath = join(
  1503. pluginStorageRoot,
  1504. "marketplaces",
  1505. "zcode-plugins-official",
  1506. "marketplace.json",
  1507. );
  1508. const manifest = JSON.parse(await readFile(manifestPath, "utf8")) as {
  1509. plugins: Array<Record<string, unknown>>;
  1510. };
  1511. const entry = manifest.plugins.find((plugin) => plugin.name === "documents");
  1512. expect(entry).toBeDefined();
  1513. entry!.source = { source: "directory", path: cdnSourceRoot };
  1514. entry!.version = "1.0.0";
  1515. await writeFile(manifestPath, JSON.stringify(manifest));
  1516. const result = await installZCodeMarketplacePlugin({
  1517. marketplace: "zcode-plugins-official",
  1518. pluginName: "documents",
  1519. pluginStorageRoot,
  1520. userConfigPath,
  1521. workingDirectory: root,
  1522. });
  1523. expect(result.diagnostics).toEqual([]);
  1524. const config = JSON.parse(await readFile(userConfigPath, "utf8")) as {
  1525. plugins?: { suppressedBuiltins?: string[] };
  1526. };
  1527. expect(config.plugins?.suppressedBuiltins ?? []).not.toContain(DOCUMENTS_PLUGIN_ID);
  1528. expect(existsSync(join(pluginStorageRoot, "installed_plugins.json"))).toBe(true);
  1529. } finally {
  1530. await rm(root, { force: true, recursive: true });
  1531. }
  1532. });
  1533. it("returns null when uninstalling a plugin that is not installed", async () => {
  1534. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-uninstall-missing-"));
  1535. const pluginStorageRoot = join(root, "plugins");
  1536. try {
  1537. const removed = await uninstallZCodeMarketplacePlugin({
  1538. pluginId: "missing@lazy-market",
  1539. pluginStorageRoot,
  1540. skipUserConfig: true,
  1541. workingDirectory: root,
  1542. });
  1543. expect(removed).toBeNull();
  1544. } finally {
  1545. await rm(root, { force: true, recursive: true });
  1546. }
  1547. });
  1548. it("returns diagnostics when lazy marketplace refresh fails during validation", async () => {
  1549. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-lazy-marketplace-offline-"));
  1550. const pluginStorageRoot = join(root, "plugins");
  1551. try {
  1552. await writeKnownMarketplaces(pluginStorageRoot, [
  1553. {
  1554. id: "offline-market",
  1555. source: {
  1556. source: "directory",
  1557. path: join(root, "missing-marketplace"),
  1558. },
  1559. name: "offline-market",
  1560. addedAt: "2026-01-01T00:00:00.000Z",
  1561. pluginCount: 0,
  1562. },
  1563. ]);
  1564. const diagnostics = await validateZCodePlugin({
  1565. marketplace: "offline-market",
  1566. pluginName: "hello",
  1567. pluginStorageRoot,
  1568. workingDirectory: root,
  1569. });
  1570. expect(diagnostics).toEqual([
  1571. expect.objectContaining({
  1572. code: "plugin_marketplace_invalid",
  1573. pluginId: "hello@offline-market",
  1574. severity: "error",
  1575. }),
  1576. ]);
  1577. } finally {
  1578. await rm(root, { force: true, recursive: true });
  1579. }
  1580. });
  1581. it("returns and persists marketplace refresh diagnostics while keeping the last snapshot", async () => {
  1582. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-marketplace-refresh-failure-"));
  1583. const pluginStorageRoot = join(root, "plugins");
  1584. const snapshotRoot = join(pluginStorageRoot, "marketplaces", "offline-market");
  1585. try {
  1586. await mkdir(snapshotRoot, { recursive: true });
  1587. await writeFile(
  1588. join(snapshotRoot, "marketplace.json"),
  1589. JSON.stringify({
  1590. name: "offline-market",
  1591. plugins: [{ name: "cached", source: "./cached" }],
  1592. }),
  1593. );
  1594. await writeKnownMarketplaces(pluginStorageRoot, [
  1595. {
  1596. id: "offline-market",
  1597. source: {
  1598. source: "directory",
  1599. path: join(root, "missing-marketplace"),
  1600. },
  1601. name: "offline-market",
  1602. addedAt: "2026-01-01T00:00:00.000Z",
  1603. lastUpdated: "2026-01-02T00:00:00.000Z",
  1604. pluginCount: 1,
  1605. },
  1606. ]);
  1607. const update = await updateZCodePluginMarketplace({
  1608. marketplace: "offline-market",
  1609. pluginStorageRoot,
  1610. workingDirectory: root,
  1611. });
  1612. const overview = await getZCodePluginsOverview({
  1613. pluginStorageRoot,
  1614. skipUserConfig: true,
  1615. workingDirectory: root,
  1616. });
  1617. expect(update.marketplaces).toEqual([]);
  1618. expect(update.diagnostics).toEqual([
  1619. expect.objectContaining({
  1620. code: "plugin_marketplace_invalid",
  1621. pluginId: "offline-market",
  1622. severity: "error",
  1623. }),
  1624. ]);
  1625. expect(overview.marketplaces.find((item) => item.id === "offline-market")).toMatchObject({
  1626. lastUpdated: "2026-01-02T00:00:00.000Z",
  1627. pluginCount: 1,
  1628. refreshFailure: {
  1629. code: "plugin_marketplace_invalid",
  1630. failedAt: expect.any(String),
  1631. },
  1632. });
  1633. expect(overview.availablePlugins).toContainEqual(
  1634. expect.objectContaining({ id: "cached@offline-market" }),
  1635. );
  1636. expect(overview.diagnostics).toContainEqual(
  1637. expect.objectContaining({
  1638. code: "plugin_marketplace_invalid",
  1639. pluginId: "offline-market",
  1640. }),
  1641. );
  1642. } finally {
  1643. await rm(root, { force: true, recursive: true });
  1644. }
  1645. });
  1646. it("returns plugin_git_unavailable for an install source that requires system Git", async () => {
  1647. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-plugin-git-unavailable-"));
  1648. const pluginStorageRoot = join(root, "plugins");
  1649. const snapshotRoot = join(pluginStorageRoot, "marketplaces", "private-market");
  1650. try {
  1651. await mkdir(snapshotRoot, { recursive: true });
  1652. await writeFile(
  1653. join(snapshotRoot, "marketplace.json"),
  1654. JSON.stringify({
  1655. name: "private-market",
  1656. plugins: [
  1657. {
  1658. name: "private-plugin",
  1659. source: {
  1660. source: "git",
  1661. url: "ssh://git@example.test/private/plugin.git",
  1662. },
  1663. },
  1664. ],
  1665. }),
  1666. );
  1667. await writeKnownMarketplaces(pluginStorageRoot, [
  1668. {
  1669. id: "private-market",
  1670. source: { source: "directory", path: join(root, "unused") },
  1671. name: "private-market",
  1672. addedAt: "2026-01-01T00:00:00.000Z",
  1673. pluginCount: 1,
  1674. },
  1675. ]);
  1676. vi.stubEnv("PATH", join(root, "no-system-git"));
  1677. const result = await installZCodeMarketplacePlugin({
  1678. marketplace: "private-market",
  1679. pluginName: "private-plugin",
  1680. pluginStorageRoot,
  1681. skipUserConfig: true,
  1682. workingDirectory: root,
  1683. });
  1684. expect(result.installedPlugins).toEqual([]);
  1685. expect(result.diagnostics).toEqual([
  1686. expect.objectContaining({
  1687. code: "plugin_git_unavailable",
  1688. pluginId: "private-plugin@private-market",
  1689. severity: "error",
  1690. }),
  1691. ]);
  1692. } finally {
  1693. await rm(root, { force: true, recursive: true });
  1694. }
  1695. });
  1696. it("preserves hook executable mode when rebuilding an older filesystem version", async () => {
  1697. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-plugin-mode-reseed-"));
  1698. const entryRoot = join(root, "resources", "glm");
  1699. const pluginStorageRoot = join(root, "plugins");
  1700. // 用仍登记的官方插件(skill-creator)做载体;文件全是 fixture 伪造的,
  1701. // 真实 skill-creator 是否带 hook 无关紧要——seed 逻辑按伪造目录 reseed。
  1702. const pluginRoot = join(entryRoot, "packages", "skill-creator-plugin");
  1703. const targetRoot = join(pluginStorageRoot, OFFICIAL_SKILL_CREATOR_PLUGIN_CACHE_PATH);
  1704. const originalEntrypoint = process.argv[1];
  1705. try {
  1706. await writeTestFile(join(entryRoot, "zcode.cjs"), "");
  1707. await writeTestFile(
  1708. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  1709. JSON.stringify({
  1710. name: "skill-creator",
  1711. skills: "skills",
  1712. version: "0.1.0",
  1713. }),
  1714. );
  1715. await writeTestFile(join(pluginRoot, "hooks", "hooks.json"), "{}");
  1716. await writeExecutableTestFile(
  1717. join(pluginRoot, "hooks", "run-hook.cmd"),
  1718. "#!/usr/bin/env bash\n",
  1719. );
  1720. await writeTestFile(join(pluginRoot, "skills", "skill-creator", "SKILL.md"), "# skill");
  1721. await writeTestFile(
  1722. join(targetRoot, ".zcode-plugin", "plugin.json"),
  1723. JSON.stringify({ name: "skill-creator" }),
  1724. );
  1725. await writeTestFile(join(targetRoot, "hooks", "run-hook.cmd"), "#!/usr/bin/env bash\n");
  1726. await writeTestFile(
  1727. join(targetRoot, ".zcode-plugin-seed.json"),
  1728. JSON.stringify({
  1729. marketplace: "zcode-plugins-official",
  1730. plugin: "skill-creator",
  1731. pluginVersion: "0.0.0",
  1732. source: "filesystem",
  1733. version: 1,
  1734. }),
  1735. );
  1736. expect((await stat(join(targetRoot, "hooks", "run-hook.cmd"))).mode & 0o111).toBe(0);
  1737. process.argv[1] = join(entryRoot, "zcode.cjs");
  1738. await resolveOfficialPluginRoots({ storageRoot: pluginStorageRoot });
  1739. expect((await stat(join(targetRoot, "hooks", "run-hook.cmd"))).mode & 0o111).not.toBe(0);
  1740. } finally {
  1741. process.argv[1] = originalEntrypoint;
  1742. await rm(root, { force: true, recursive: true });
  1743. }
  1744. });
  1745. it("projects restore legacy sessions skills and commands only when enabled", async () => {
  1746. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-restore-plugin-enabled-"));
  1747. const configPath = join(root, "config.json");
  1748. const pluginStorageRoot = join(root, "plugins");
  1749. try {
  1750. await writeFile(
  1751. configPath,
  1752. JSON.stringify({
  1753. plugins: {
  1754. enabledPlugins: {
  1755. [RESTORE_LEGACY_SESSIONS_PLUGIN_ID]: true,
  1756. },
  1757. },
  1758. }),
  1759. );
  1760. const outcome = await resolveZCodePlugins({
  1761. env: {},
  1762. pluginStorageRoot,
  1763. userConfigPath: configPath,
  1764. workingDirectory: root,
  1765. });
  1766. const plugin = outcome.plugins.find((item) => item.id === RESTORE_LEGACY_SESSIONS_PLUGIN_ID);
  1767. const expectedRoot = join(
  1768. pluginStorageRoot,
  1769. OFFICIAL_RESTORE_LEGACY_SESSIONS_PLUGIN_CACHE_PATH,
  1770. );
  1771. expect(plugin).toMatchObject({
  1772. commandRootCount: 1,
  1773. declaredMcpServerNames: [],
  1774. enabled: true,
  1775. mcpServerNames: [],
  1776. name: "restore-legacy-sessions",
  1777. rootPath: expectedRoot,
  1778. skillCount: 1,
  1779. skillRootCount: 1,
  1780. });
  1781. expect(outcome.skillRoots).toEqual(
  1782. expect.arrayContaining([
  1783. expect.objectContaining({
  1784. path: join(expectedRoot, "skills"),
  1785. scope: "system",
  1786. source: "plugin",
  1787. }),
  1788. ]),
  1789. );
  1790. expect(outcome.commandRoots).toEqual(
  1791. expect.arrayContaining([
  1792. expect.objectContaining({
  1793. path: join(expectedRoot, "commands"),
  1794. scope: "system",
  1795. source: "plugin",
  1796. }),
  1797. ]),
  1798. );
  1799. expect(Object.keys(outcome.mcpServers)).not.toContain("restore-legacy-sessions");
  1800. } finally {
  1801. await rm(root, { force: true, recursive: true });
  1802. }
  1803. });
  1804. it("projects bundled iOS simulator skills, commands, and MCP when enabled", async () => {
  1805. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-plugins-enabled-"));
  1806. const configPath = join(root, "config.json");
  1807. const pluginStorageRoot = join(root, "plugins");
  1808. try {
  1809. await writeFile(
  1810. configPath,
  1811. JSON.stringify({
  1812. plugins: {
  1813. enabledPlugins: {
  1814. [IOS_SIMULATOR_PLUGIN_ID]: true,
  1815. },
  1816. },
  1817. }),
  1818. );
  1819. const outcome = await resolveZCodePlugins({
  1820. env: {},
  1821. pluginStorageRoot,
  1822. userConfigPath: configPath,
  1823. workingDirectory: root,
  1824. });
  1825. const plugin = outcome.plugins.find((item) => item.id === IOS_SIMULATOR_PLUGIN_ID);
  1826. const server = outcome.mcpServers[IOS_SIMULATOR_MCP_ID];
  1827. const expectedRoot = join(pluginStorageRoot, OFFICIAL_PLUGIN_CACHE_PATH);
  1828. expect(plugin).toMatchObject({
  1829. commandRootCount: 1,
  1830. declaredMcpServerNames: ["ios-simulator"],
  1831. enabled: true,
  1832. mcpServerNames: [IOS_SIMULATOR_MCP_ID],
  1833. rootPath: expectedRoot,
  1834. skillCount: 1,
  1835. skillRootCount: 1,
  1836. });
  1837. expect(server).toMatchObject({
  1838. command: process.execPath,
  1839. type: "stdio",
  1840. cwd: root,
  1841. env: {
  1842. ELECTRON_RUN_AS_NODE: "1",
  1843. IOS_SIM_DEFAULT_DEVICE: "iPhone 16",
  1844. IOS_SIM_UI_BACKEND: "auto",
  1845. },
  1846. });
  1847. expect(server?.args?.at(-2)).toBe(ZCODE_PLUGIN_HOST_COMMAND);
  1848. expect(server?.args?.at(-1)).toContain(
  1849. join(
  1850. "cache",
  1851. "zcode-plugins-official",
  1852. "ios-simulator",
  1853. "0.1.0",
  1854. "dist",
  1855. "mcp",
  1856. "server.js",
  1857. ),
  1858. );
  1859. await expect(
  1860. readFile(
  1861. join(pluginStorageRoot, "marketplaces", "zcode-plugins-official", "marketplace.json"),
  1862. "utf8",
  1863. ),
  1864. ).resolves.toContain(IOS_SIMULATOR_PLUGIN_ID.split("@")[0] ?? "ios-simulator");
  1865. expect(existsSync(join(expectedRoot, ".zcode-plugin-seed.json"))).toBe(true);
  1866. expect(existsSync(join(expectedRoot, "dist", "mcp", "server.js"))).toBe(
  1867. existsSync(BUNDLED_PLUGIN_DIST_PATH),
  1868. );
  1869. expect(outcome.diagnostics).not.toEqual(
  1870. expect.arrayContaining([
  1871. expect.objectContaining({
  1872. code: "plugin_unsupported_component",
  1873. pluginId: IOS_SIMULATOR_PLUGIN_ID,
  1874. }),
  1875. ]),
  1876. );
  1877. } finally {
  1878. await rm(root, { force: true, recursive: true });
  1879. }
  1880. });
  1881. it("projects bundled Android emulator skills, commands, and MCP when enabled", async () => {
  1882. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-plugins-android-enabled-"));
  1883. const configPath = join(root, "config.json");
  1884. const pluginStorageRoot = join(root, "plugins");
  1885. try {
  1886. await writeFile(
  1887. configPath,
  1888. JSON.stringify({
  1889. plugins: {
  1890. enabledPlugins: {
  1891. [ANDROID_EMULATOR_PLUGIN_ID]: true,
  1892. },
  1893. options: {
  1894. [ANDROID_EMULATOR_PLUGIN_ID]: {
  1895. api_level: "36",
  1896. default_avd: "Pixel_8",
  1897. },
  1898. },
  1899. },
  1900. }),
  1901. );
  1902. const outcome = await resolveZCodePlugins({
  1903. env: {},
  1904. pluginStorageRoot,
  1905. userConfigPath: configPath,
  1906. workingDirectory: root,
  1907. });
  1908. const plugin = outcome.plugins.find((item) => item.id === ANDROID_EMULATOR_PLUGIN_ID);
  1909. const server = outcome.mcpServers[ANDROID_EMULATOR_MCP_ID];
  1910. const expectedRoot = join(pluginStorageRoot, OFFICIAL_ANDROID_PLUGIN_CACHE_PATH);
  1911. expect(plugin).toMatchObject({
  1912. commandRootCount: 1,
  1913. declaredMcpServerNames: ["android-emulator"],
  1914. enabled: true,
  1915. mcpServerNames: [ANDROID_EMULATOR_MCP_ID],
  1916. rootPath: expectedRoot,
  1917. skillCount: 1,
  1918. skillRootCount: 1,
  1919. });
  1920. expect(server).toMatchObject({
  1921. command: process.execPath,
  1922. type: "stdio",
  1923. cwd: root,
  1924. env: {
  1925. ANDROID_PLUGIN_API_LEVEL: "36",
  1926. ANDROID_PLUGIN_DEFAULT_AVD: "Pixel_8",
  1927. ELECTRON_RUN_AS_NODE: "1",
  1928. },
  1929. });
  1930. for (const unusedEnv of [
  1931. "ANDROID_PLUGIN_ROOT",
  1932. "ANDROID_PLUGIN_DEFAULT_PROFILE",
  1933. "ANDROID_PLUGIN_WINDOWS_JDK_WINGET_PACKAGE",
  1934. "ANDROID_PLUGIN_CMDLINE_TOOLS_VERSION",
  1935. "ANDROID_PLUGIN_CMDLINE_TOOLS_CHECKSUM",
  1936. "ANDROID_PLUGIN_CMDLINE_TOOLS_CHECKSUM_ALGORITHM",
  1937. ]) {
  1938. expect(server?.env).not.toHaveProperty(unusedEnv);
  1939. }
  1940. expect(server?.args?.at(-2)).toBe(ZCODE_PLUGIN_HOST_COMMAND);
  1941. expect(server?.args?.at(-1)).toContain(
  1942. join(
  1943. "cache",
  1944. "zcode-plugins-official",
  1945. "android-emulator",
  1946. "0.1.1",
  1947. "dist",
  1948. "mcp",
  1949. "server.js",
  1950. ),
  1951. );
  1952. expect(existsSync(join(expectedRoot, ".zcode-plugin-seed.json"))).toBe(true);
  1953. expect(existsSync(join(expectedRoot, "dist", "mcp", "server.js"))).toBe(
  1954. existsSync(BUNDLED_ANDROID_PLUGIN_DIST_PATH),
  1955. );
  1956. expect(outcome.diagnostics).not.toEqual(
  1957. expect.arrayContaining([
  1958. expect.objectContaining({
  1959. code: "plugin_unsupported_component",
  1960. pluginId: ANDROID_EMULATOR_PLUGIN_ID,
  1961. }),
  1962. ]),
  1963. );
  1964. } finally {
  1965. await rm(root, { force: true, recursive: true });
  1966. }
  1967. });
  1968. it("persists sensitive plugin options in the selected User or Workspace config", async () => {
  1969. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-plugin-options-"));
  1970. const userConfigPath = join(root, "user-config.json");
  1971. const workspaceConfigPath = join(root, ".zcode", "config.json");
  1972. const pluginStorageRoot = join(root, "plugins");
  1973. const pluginRoot = join(root, "secret-plugin");
  1974. const pluginId = "secret-plugin@inline";
  1975. try {
  1976. await writeTestFile(
  1977. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  1978. JSON.stringify({
  1979. name: "secret-plugin",
  1980. userConfig: {
  1981. token: {
  1982. sensitive: true,
  1983. type: "string",
  1984. },
  1985. region: {
  1986. type: "string",
  1987. },
  1988. },
  1989. }),
  1990. );
  1991. await writeTestFile(
  1992. userConfigPath,
  1993. JSON.stringify({
  1994. plugins: {
  1995. dirs: [pluginRoot],
  1996. },
  1997. }),
  1998. );
  1999. await configureZCodePlugin({
  2000. options: { region: "us-east-1" },
  2001. pluginId,
  2002. pluginStorageRoot,
  2003. userConfigPath,
  2004. workingDirectory: root,
  2005. });
  2006. await configureZCodePlugin({
  2007. options: { token: "secret" },
  2008. pluginId,
  2009. pluginStorageRoot,
  2010. projectConfigPath: workspaceConfigPath,
  2011. scope: "workspace",
  2012. userConfigPath,
  2013. workingDirectory: root,
  2014. });
  2015. expect(JSON.parse(await readFile(userConfigPath, "utf8"))).toMatchObject({
  2016. plugins: { dirs: [pluginRoot] },
  2017. });
  2018. const reloadedConfig = createConfig({
  2019. env: {},
  2020. projectConfigPath: workspaceConfigPath,
  2021. userConfigPath,
  2022. workingDirectory: root,
  2023. });
  2024. expect(reloadedConfig.sources.plugins.dirs).toEqual({
  2025. user: [pluginRoot],
  2026. workspace: [],
  2027. });
  2028. expect(reloadedConfig.config.plugins.dirs).toEqual([pluginRoot]);
  2029. expect(
  2030. (
  2031. await resolveZCodePlugins({
  2032. configResult: reloadedConfig,
  2033. pluginStorageRoot,
  2034. workingDirectory: root,
  2035. })
  2036. ).plugins.map((plugin) => plugin.id),
  2037. ).toContain(pluginId);
  2038. await configureZCodePlugin({
  2039. options: { region: "eu-west-1" },
  2040. pluginId,
  2041. pluginStorageRoot,
  2042. projectConfigPath: workspaceConfigPath,
  2043. scope: "workspace",
  2044. userConfigPath,
  2045. workingDirectory: root,
  2046. });
  2047. await setZCodePluginEnabled({
  2048. enabled: true,
  2049. plugin: pluginId,
  2050. pluginStorageRoot,
  2051. projectConfigPath: workspaceConfigPath,
  2052. scope: "workspace",
  2053. userConfigPath,
  2054. workingDirectory: root,
  2055. });
  2056. await configureZCodePlugin({
  2057. clearOptionKeys: ["token"],
  2058. options: {},
  2059. pluginId,
  2060. pluginStorageRoot,
  2061. projectConfigPath: workspaceConfigPath,
  2062. scope: "workspace",
  2063. userConfigPath,
  2064. workingDirectory: root,
  2065. });
  2066. const userConfig = JSON.parse(await readFile(userConfigPath, "utf8")) as {
  2067. plugins?: { options?: Record<string, Record<string, unknown>> };
  2068. };
  2069. const workspaceConfig = JSON.parse(await readFile(workspaceConfigPath, "utf8")) as {
  2070. plugins?: {
  2071. enabledPlugins?: Record<string, boolean>;
  2072. options?: Record<string, Record<string, unknown>>;
  2073. };
  2074. };
  2075. expect(userConfig.plugins?.options?.[pluginId]?.region).toBe("us-east-1");
  2076. expect(userConfig.plugins?.options?.[pluginId]?.token).toBeUndefined();
  2077. expect(workspaceConfig.plugins?.enabledPlugins?.[pluginId]).toBe(true);
  2078. expect(workspaceConfig.plugins?.options?.[pluginId]?.token).toBeUndefined();
  2079. expect(workspaceConfig.plugins?.options?.[pluginId]?.region).toBe("eu-west-1");
  2080. } finally {
  2081. await rm(root, { force: true, recursive: true });
  2082. }
  2083. });
  2084. it("writes Workspace enablement without mutating User config", async () => {
  2085. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-plugin-scope-"));
  2086. const userConfigPath = join(root, "user-config.json");
  2087. const workspaceConfigPath = join(root, ".zcode", "config.json");
  2088. const pluginStorageRoot = join(root, "plugins");
  2089. const pluginRoot = join(root, "workspace-plugin");
  2090. const pluginId = "workspace-plugin@inline";
  2091. try {
  2092. await writeTestFile(
  2093. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  2094. JSON.stringify({ name: "workspace-plugin", userConfig: {} }),
  2095. );
  2096. await writeTestFile(userConfigPath, JSON.stringify({ plugins: { dirs: [pluginRoot] } }));
  2097. await writeTestFile(
  2098. join(root, "zcode.json"),
  2099. JSON.stringify({
  2100. mcp: {
  2101. servers: { keep: { type: "http", url: "https://example.test" } },
  2102. },
  2103. }),
  2104. );
  2105. const result = await setZCodePluginEnabled({
  2106. enabled: true,
  2107. plugin: pluginId,
  2108. pluginStorageRoot,
  2109. scope: "workspace",
  2110. userConfigPath,
  2111. workingDirectory: root,
  2112. });
  2113. expect(result.enabled).toBe(true);
  2114. expect(JSON.parse(await readFile(userConfigPath, "utf8"))).toEqual({
  2115. plugins: { dirs: [pluginRoot] },
  2116. });
  2117. expect(JSON.parse(await readFile(workspaceConfigPath, "utf8"))).toEqual({
  2118. plugins: { enabledPlugins: { [pluginId]: true } },
  2119. });
  2120. expect(JSON.parse(await readFile(join(root, "zcode.json"), "utf8"))).toEqual({
  2121. mcp: {
  2122. servers: { keep: { type: "http", url: "https://example.test" } },
  2123. },
  2124. });
  2125. } finally {
  2126. await rm(root, { force: true, recursive: true });
  2127. }
  2128. });
  2129. it("writes nested Workspace plugin state to the Workspace-owned config", async () => {
  2130. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-nested-plugin-scope-"));
  2131. const repositoryRoot = join(root, "repository");
  2132. const workspaceRoot = join(repositoryRoot, "packages", "app");
  2133. const repositoryConfigPath = join(repositoryRoot, ".zcode", "config.json");
  2134. const workspaceConfigPath = join(workspaceRoot, ".zcode", "config.json");
  2135. const userConfigPath = join(root, "user-config.json");
  2136. const pluginRoot = join(root, "workspace-plugin");
  2137. const pluginId = "workspace-plugin@inline";
  2138. try {
  2139. await mkdir(join(repositoryRoot, ".git"), { recursive: true });
  2140. await writeTestFile(
  2141. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  2142. JSON.stringify({ name: "workspace-plugin", userConfig: {} }),
  2143. );
  2144. await writeTestFile(userConfigPath, JSON.stringify({ plugins: { dirs: [pluginRoot] } }));
  2145. await writeTestFile(
  2146. repositoryConfigPath,
  2147. JSON.stringify({ plugins: { enabledPlugins: { [pluginId]: false } } }),
  2148. );
  2149. await writeTestFile(
  2150. workspaceConfigPath,
  2151. JSON.stringify({
  2152. plugins: { options: { [pluginId]: { region: "nested" } } },
  2153. }),
  2154. );
  2155. await setZCodePluginEnabled({
  2156. enabled: true,
  2157. plugin: pluginId,
  2158. pluginStorageRoot: join(root, "plugins"),
  2159. scope: "workspace",
  2160. userConfigPath,
  2161. workingDirectory: workspaceRoot,
  2162. });
  2163. expect(JSON.parse(await readFile(repositoryConfigPath, "utf8"))).toEqual({
  2164. plugins: { enabledPlugins: { [pluginId]: false } },
  2165. });
  2166. expect(JSON.parse(await readFile(workspaceConfigPath, "utf8"))).toEqual({
  2167. plugins: {
  2168. enabledPlugins: { [pluginId]: true },
  2169. options: { [pluginId]: { region: "nested" } },
  2170. },
  2171. });
  2172. const reloaded = createConfig({
  2173. env: {},
  2174. userConfigPath,
  2175. workingDirectory: workspaceRoot,
  2176. });
  2177. expect(reloaded.config.plugins.enabledPlugins[pluginId]).toBe(true);
  2178. expect(reloaded.sources.plugins.enabled[pluginId]).toBe("workspace");
  2179. } finally {
  2180. await rm(root, { force: true, recursive: true });
  2181. }
  2182. });
  2183. it("resets Workspace plugin keys so effective config inherits User", async () => {
  2184. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-plugin-reset-"));
  2185. const userConfigPath = join(root, "user-config.json");
  2186. const workspaceConfigPath = join(root, ".zcode", "config.json");
  2187. const pluginId = "workspace-plugin@inline";
  2188. try {
  2189. await writeTestFile(
  2190. userConfigPath,
  2191. JSON.stringify({
  2192. plugins: {
  2193. enabledPlugins: { [pluginId]: true },
  2194. options: { [pluginId]: { label: "user" } },
  2195. },
  2196. }),
  2197. );
  2198. await writeTestFile(
  2199. workspaceConfigPath,
  2200. JSON.stringify({
  2201. plugins: {
  2202. enabledPlugins: { [pluginId]: false },
  2203. options: { [pluginId]: { label: "workspace" } },
  2204. },
  2205. }),
  2206. );
  2207. await resetZCodePluginConfig({
  2208. pluginId,
  2209. scope: "workspace",
  2210. projectConfigPath: workspaceConfigPath,
  2211. userConfigPath,
  2212. workingDirectory: root,
  2213. });
  2214. expect(JSON.parse(await readFile(workspaceConfigPath, "utf8"))).toEqual({
  2215. plugins: {
  2216. enabledPlugins: {},
  2217. options: { [pluginId]: { label: "workspace" } },
  2218. },
  2219. });
  2220. expect(JSON.parse(await readFile(userConfigPath, "utf8"))).toEqual({
  2221. plugins: {
  2222. enabledPlugins: { [pluginId]: true },
  2223. options: { [pluginId]: { label: "user" } },
  2224. },
  2225. });
  2226. } finally {
  2227. await rm(root, { force: true, recursive: true });
  2228. }
  2229. });
  2230. it("keeps Marketplace default enablement in User config for a legacy Workspace scope", async () => {
  2231. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-user-marketplace-"));
  2232. const pluginStorageRoot = join(root, "plugins");
  2233. const marketplaceRoot = join(root, "user-marketplace");
  2234. const pluginRoot = join(marketplaceRoot, "plugins", "workspace-demo");
  2235. const userConfigPath = join(root, "user-config.json");
  2236. const workspaceConfigPath = join(root, ".zcode", "config.json");
  2237. const marketplaceId = "workspace-market";
  2238. const pluginName = "workspace-demo";
  2239. try {
  2240. await writeTestFile(
  2241. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  2242. JSON.stringify({
  2243. name: marketplaceId,
  2244. plugins: [
  2245. {
  2246. name: pluginName,
  2247. source: "./plugins/workspace-demo",
  2248. version: "1.0.0",
  2249. },
  2250. ],
  2251. }),
  2252. );
  2253. await writeTestFile(
  2254. join(pluginRoot, ".claude-plugin", "plugin.json"),
  2255. JSON.stringify({
  2256. name: pluginName,
  2257. skills: "skills",
  2258. version: "1.0.0",
  2259. }),
  2260. );
  2261. await writeTestFile(join(pluginRoot, "skills", pluginName, "SKILL.md"), "# workspace demo");
  2262. await writeTestFile(
  2263. userConfigPath,
  2264. JSON.stringify({
  2265. plugins: {
  2266. extraKnownMarketplaces: {
  2267. [marketplaceId]: {
  2268. source: { source: "directory", path: marketplaceRoot },
  2269. },
  2270. },
  2271. },
  2272. }),
  2273. );
  2274. const beforeRefresh = await getZCodePluginsOverview({
  2275. env: {},
  2276. pluginStorageRoot,
  2277. userConfigPath,
  2278. workingDirectory: root,
  2279. });
  2280. expect(beforeRefresh.marketplaces).toEqual(
  2281. expect.arrayContaining([
  2282. expect.objectContaining({
  2283. id: marketplaceId,
  2284. pluginCount: 0,
  2285. source: { source: "directory", path: marketplaceRoot },
  2286. }),
  2287. ]),
  2288. );
  2289. expect(beforeRefresh.availablePlugins).not.toEqual(
  2290. expect.arrayContaining([expect.objectContaining({ id: `${pluginName}@${marketplaceId}` })]),
  2291. );
  2292. expect(existsSync(join(pluginStorageRoot, "marketplaces", marketplaceId))).toBe(false);
  2293. const knownBeforeRefresh = JSON.parse(
  2294. await readFile(join(pluginStorageRoot, "known_marketplaces.json"), "utf8"),
  2295. ) as { marketplaces: Array<{ id: string }> };
  2296. expect(knownBeforeRefresh.marketplaces.some((item) => item.id === marketplaceId)).toBe(false);
  2297. const dryRun = await installZCodeMarketplacePlugin({
  2298. dryRun: true,
  2299. env: {},
  2300. marketplace: marketplaceId,
  2301. pluginName,
  2302. pluginStorageRoot,
  2303. userConfigPath,
  2304. workingDirectory: root,
  2305. });
  2306. expect(dryRun.diagnostics).toEqual([]);
  2307. expect(existsSync(join(pluginStorageRoot, "marketplaces", marketplaceId))).toBe(false);
  2308. const refreshed = await updateZCodePluginMarketplace({
  2309. env: {},
  2310. marketplace: marketplaceId,
  2311. pluginStorageRoot,
  2312. userConfigPath,
  2313. workingDirectory: root,
  2314. });
  2315. expect(refreshed.diagnostics).toEqual([]);
  2316. expect(refreshed.marketplaces).toEqual([
  2317. expect.objectContaining({ id: marketplaceId, pluginCount: 1 }),
  2318. ]);
  2319. expect(
  2320. existsSync(join(pluginStorageRoot, "marketplaces", marketplaceId, "marketplace.json")),
  2321. ).toBe(true);
  2322. const afterRefresh = await getZCodePluginsOverview({
  2323. env: {},
  2324. pluginStorageRoot,
  2325. userConfigPath,
  2326. workingDirectory: root,
  2327. });
  2328. expect(afterRefresh.availablePlugins).toEqual(
  2329. expect.arrayContaining([
  2330. expect.objectContaining({
  2331. id: `${pluginName}@${marketplaceId}`,
  2332. installed: false,
  2333. }),
  2334. ]),
  2335. );
  2336. const installed = await installZCodeMarketplacePlugin({
  2337. env: {},
  2338. marketplace: marketplaceId,
  2339. pluginName,
  2340. pluginStorageRoot,
  2341. userConfigPath,
  2342. scope: "workspace",
  2343. workingDirectory: root,
  2344. });
  2345. expect(installed.diagnostics).toEqual([]);
  2346. expect(installed.installedPlugins).toEqual([
  2347. expect.objectContaining({
  2348. id: `${pluginName}@${marketplaceId}`,
  2349. // Package inventory and the default enablement are both Host/User state.
  2350. scope: "user",
  2351. }),
  2352. ]);
  2353. expect(JSON.parse(await readFile(userConfigPath, "utf8"))).toMatchObject({
  2354. plugins: {
  2355. enabledPlugins: { [`${pluginName}@${marketplaceId}`]: true },
  2356. extraKnownMarketplaces: {
  2357. [marketplaceId]: {
  2358. source: { source: "directory", path: marketplaceRoot },
  2359. },
  2360. },
  2361. },
  2362. });
  2363. expect(existsSync(workspaceConfigPath)).toBe(false);
  2364. expect(
  2365. JSON.parse(await readFile(join(pluginStorageRoot, "installed_plugins.json"), "utf8")),
  2366. ).toMatchObject({
  2367. plugins: [
  2368. expect.objectContaining({
  2369. id: `${pluginName}@${marketplaceId}`,
  2370. scope: "user",
  2371. }),
  2372. ],
  2373. });
  2374. } finally {
  2375. await rm(root, { force: true, recursive: true });
  2376. }
  2377. });
  2378. it("ignores Marketplace declarations from Workspace config", async () => {
  2379. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-ignore-workspace-marketplace-"));
  2380. const marketplaceId = "workspace-market";
  2381. try {
  2382. await writeTestFile(
  2383. join(root, ".zcode", "config.json"),
  2384. JSON.stringify({
  2385. plugins: {
  2386. extraKnownMarketplaces: {
  2387. [marketplaceId]: {
  2388. source: {
  2389. source: "directory",
  2390. path: join(root, "marketplace"),
  2391. },
  2392. },
  2393. },
  2394. },
  2395. }),
  2396. );
  2397. const configResult = createConfig({
  2398. env: {},
  2399. userConfigPath: join(root, "user-config.json"),
  2400. workingDirectory: root,
  2401. });
  2402. expect(configResult.config.plugins?.extraKnownMarketplaces?.[marketplaceId]).toBeUndefined();
  2403. const overview = await getZCodePluginsOverview({
  2404. env: {},
  2405. pluginStorageRoot: join(root, "plugins"),
  2406. userConfigPath: join(root, "user-config.json"),
  2407. workingDirectory: root,
  2408. });
  2409. expect(overview.marketplaces).not.toEqual(
  2410. expect.arrayContaining([expect.objectContaining({ id: marketplaceId })]),
  2411. );
  2412. } finally {
  2413. await rm(root, { force: true, recursive: true });
  2414. }
  2415. });
  2416. it("resolves User relative marketplace paths from the declaring config directory", async () => {
  2417. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-user-marketplace-path-"));
  2418. const userConfigPath = join(root, "user", "config.json");
  2419. const workspacePath = join(root, "workspace");
  2420. try {
  2421. await writeTestFile(
  2422. userConfigPath,
  2423. JSON.stringify({
  2424. plugins: {
  2425. extraKnownMarketplaces: {
  2426. "user-market": {
  2427. source: { source: "directory", path: "./marketplace" },
  2428. },
  2429. },
  2430. },
  2431. }),
  2432. );
  2433. const overview = await getZCodePluginsOverview({
  2434. env: {},
  2435. pluginStorageRoot: join(root, "plugins"),
  2436. userConfigPath,
  2437. workingDirectory: workspacePath,
  2438. });
  2439. expect(overview.marketplaces).toEqual(
  2440. expect.arrayContaining([
  2441. expect.objectContaining({
  2442. id: "user-market",
  2443. source: {
  2444. source: "directory",
  2445. path: join(root, "user", "marketplace"),
  2446. },
  2447. }),
  2448. ]),
  2449. );
  2450. } finally {
  2451. await rm(root, { force: true, recursive: true });
  2452. }
  2453. });
  2454. it("keeps official marketplace projection when User declares a reserved id", async () => {
  2455. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-reserved-marketplace-"));
  2456. const pluginStorageRoot = join(root, "plugins");
  2457. const userConfigPath = join(root, "user-config.json");
  2458. try {
  2459. await writeTestFile(
  2460. userConfigPath,
  2461. JSON.stringify({
  2462. plugins: {
  2463. extraKnownMarketplaces: {
  2464. "zcode-plugins-official": {
  2465. source: { source: "directory", path: "./untrusted-official" },
  2466. },
  2467. },
  2468. },
  2469. }),
  2470. );
  2471. const overview = await getZCodePluginsOverview({
  2472. env: {},
  2473. pluginStorageRoot,
  2474. userConfigPath,
  2475. workingDirectory: root,
  2476. });
  2477. expect(
  2478. overview.marketplaces.find((marketplace) => marketplace.id === "zcode-plugins-official"),
  2479. ).toMatchObject({
  2480. pluginCount: 16,
  2481. source: {
  2482. source: "url",
  2483. url: "https://cdn-zcode.z.ai/zcode/official-plugin/marketplace.json",
  2484. },
  2485. });
  2486. expect(overview.diagnostics).toEqual(
  2487. expect.arrayContaining([
  2488. expect.objectContaining({
  2489. code: "plugin_marketplace_declaration_reserved",
  2490. pluginId: "zcode-plugins-official",
  2491. severity: "warning",
  2492. }),
  2493. ]),
  2494. );
  2495. } finally {
  2496. await rm(root, { force: true, recursive: true });
  2497. }
  2498. });
  2499. it("does not repoint an existing Host marketplace from a Workspace declaration", async () => {
  2500. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-marketplace-repoint-"));
  2501. const pluginStorageRoot = join(root, "plugins");
  2502. const originalSource = join(root, "original-marketplace");
  2503. const workspaceSource = join(root, "workspace-marketplace");
  2504. const workspaceConfigPath = join(root, ".zcode", "config.json");
  2505. const marketplaceId = "shared-market";
  2506. try {
  2507. await writeTestFile(
  2508. join(workspaceSource, ".claude-plugin", "marketplace.json"),
  2509. JSON.stringify({ name: marketplaceId, plugins: [] }),
  2510. );
  2511. await writeKnownMarketplaces(pluginStorageRoot, [
  2512. {
  2513. id: marketplaceId,
  2514. source: { source: "directory", path: originalSource },
  2515. name: marketplaceId,
  2516. addedAt: "2026-08-19T00:00:00.000Z",
  2517. pluginCount: 0,
  2518. },
  2519. ]);
  2520. await writeTestFile(
  2521. workspaceConfigPath,
  2522. JSON.stringify({
  2523. plugins: {
  2524. extraKnownMarketplaces: {
  2525. [marketplaceId]: {
  2526. source: { source: "directory", path: workspaceSource },
  2527. },
  2528. },
  2529. },
  2530. }),
  2531. );
  2532. const result = await updateZCodePluginMarketplace({
  2533. env: {},
  2534. marketplace: marketplaceId,
  2535. pluginStorageRoot,
  2536. workingDirectory: root,
  2537. });
  2538. const persisted = JSON.parse(
  2539. await readFile(join(pluginStorageRoot, "known_marketplaces.json"), "utf8"),
  2540. ) as { marketplaces: Array<{ id: string; source: { path: string } }> };
  2541. expect(result.diagnostics).toEqual([
  2542. expect.objectContaining({
  2543. code: "plugin_marketplace_invalid",
  2544. pluginId: marketplaceId,
  2545. severity: "error",
  2546. }),
  2547. ]);
  2548. const installResult = await installZCodeMarketplacePlugin({
  2549. env: {},
  2550. marketplace: marketplaceId,
  2551. pluginName: "demo",
  2552. pluginStorageRoot,
  2553. workingDirectory: root,
  2554. });
  2555. expect(installResult.diagnostics).toEqual([
  2556. expect.objectContaining({
  2557. code: "plugin_marketplace_invalid",
  2558. pluginId: `demo@${marketplaceId}`,
  2559. severity: "error",
  2560. }),
  2561. ]);
  2562. expect(persisted.marketplaces.find((item) => item.id === marketplaceId)?.source.path).toBe(
  2563. originalSource,
  2564. );
  2565. } finally {
  2566. await rm(root, { force: true, recursive: true });
  2567. }
  2568. });
  2569. it("keeps refresh-all limited to already known marketplaces", () => {
  2570. expect(
  2571. resolveMarketplaceRefreshTargetIds({
  2572. declaredIds: ["workspace-only", "known"],
  2573. knownIds: ["known"],
  2574. }),
  2575. ).toEqual(["known"]);
  2576. expect(
  2577. resolveMarketplaceRefreshTargetIds({
  2578. declaredIds: ["workspace-only"],
  2579. knownIds: [],
  2580. marketplace: "workspace-only",
  2581. }),
  2582. ).toEqual(["workspace-only"]);
  2583. });
  2584. it("propagates cancellation while refreshing a declared marketplace", async () => {
  2585. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-marketplace-refresh-abort-"));
  2586. const pluginStorageRoot = join(root, "plugins");
  2587. const marketplaceRoot = join(root, "workspace-marketplace");
  2588. const userConfigPath = join(root, "user-config.json");
  2589. const marketplaceId = "workspace-refresh-abort";
  2590. try {
  2591. await writeTestFile(
  2592. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  2593. JSON.stringify({
  2594. name: marketplaceId,
  2595. plugins: [],
  2596. }),
  2597. );
  2598. await writeTestFile(
  2599. userConfigPath,
  2600. JSON.stringify({
  2601. plugins: {
  2602. extraKnownMarketplaces: {
  2603. [marketplaceId]: {
  2604. source: { source: "directory", path: marketplaceRoot },
  2605. },
  2606. },
  2607. },
  2608. }),
  2609. );
  2610. const controller = new AbortController();
  2611. controller.abort();
  2612. const result = await updateZCodePluginMarketplace({
  2613. abortSignal: controller.signal,
  2614. env: {},
  2615. marketplace: marketplaceId,
  2616. pluginStorageRoot,
  2617. userConfigPath,
  2618. workingDirectory: root,
  2619. });
  2620. expect(result.diagnostics).toEqual([expect.objectContaining({ severity: "error" })]);
  2621. expect(existsSync(join(pluginStorageRoot, "marketplaces", marketplaceId))).toBe(false);
  2622. // 已取消的请求连默认市场都不应登记;既没有缓存,也没有修改安装状态。
  2623. expect(existsSync(join(pluginStorageRoot, "known_marketplaces.json"))).toBe(false);
  2624. } finally {
  2625. await rm(root, { force: true, recursive: true });
  2626. }
  2627. });
  2628. it("matches Workspace config paths case-insensitively on Windows", () => {
  2629. expect(isWorkspacePluginConfigPath("C:\\repo\\.ZCODE\\CONFIG.JSON", "win32")).toBe(true);
  2630. expect(isWorkspacePluginConfigPath("C:\\repo\\zcode.json", "win32")).toBe(false);
  2631. });
  2632. // Regression for c0120fa: the app-startup discovery path must default-enable
  2633. // content-only official plugins (skill-creator) the same way the CLI subcommand
  2634. // path does. Without forwarding the default-enabled set, `/skill skill-creator`
  2635. // failed with "Skill not found" inside a session even though it was bundled.
  2636. it("default-enables skill-creator through the app-startup plugin discovery path", async () => {
  2637. const root = await mkdtemp(join(tmpdir(), "zcode-bootstrap-startup-plugins-"));
  2638. const pluginStorageRoot = join(root, "plugins");
  2639. try {
  2640. const configResult = createConfig({
  2641. env: {},
  2642. skipUserConfig: true,
  2643. workingDirectory: root,
  2644. });
  2645. const outcome = await resolveStartupPlugins({
  2646. cliStorageRoot: join(root, "cli"),
  2647. configResult,
  2648. env: {},
  2649. options: { pluginStorageRoot } as ZCodeAppOptions,
  2650. startupTimer: createNoopStartupTimer(),
  2651. workingDirectory: root,
  2652. });
  2653. const plugin = outcome.plugins.find((item) => item.id === SKILL_CREATOR_PLUGIN_ID);
  2654. const browserUsePlugin = outcome.plugins.find((item) => item.id === BROWSER_USE_PLUGIN_ID);
  2655. const documentPlugin = outcome.plugins.find((item) => item.id === DOCUMENTS_PLUGIN_ID);
  2656. expect(plugin).toMatchObject({
  2657. enabled: true,
  2658. name: "skill-creator",
  2659. skillCount: 1,
  2660. skillRootCount: 1,
  2661. });
  2662. // 0.2.0 起 documents 同时提供 docx 与 docx-viewer 两个 skill,并带查看面板的 MCP server。
  2663. expect(documentPlugin).toMatchObject({
  2664. enabled: true,
  2665. mcpServerNames: ["plugin:documents:documents"],
  2666. name: "documents",
  2667. skillCount: 2,
  2668. skillRootCount: 1,
  2669. });
  2670. // 回归原因:启动发现链路与 overview 使用同一份 browser-use 内置内容,
  2671. // web-gui-tester 加入后这里也必须稳定报告两个 skill。
  2672. expect(browserUsePlugin).toMatchObject({
  2673. enabled: true,
  2674. name: "browser-use",
  2675. skillCount: 2,
  2676. skillRootCount: 1,
  2677. });
  2678. expect(outcome.skillRoots.length).toBeGreaterThan(0);
  2679. } finally {
  2680. await rm(root, { force: true, recursive: true });
  2681. }
  2682. });
  2683. });
  2684. async function startZipFixtureServer(
  2685. routes: Record<string, Buffer>,
  2686. ): Promise<{ baseUrl: string; server: Server }> {
  2687. const server = createServer((request, response) => {
  2688. const pathname = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
  2689. const body = routes[pathname];
  2690. if (!body) {
  2691. response.writeHead(404);
  2692. response.end("not found");
  2693. return;
  2694. }
  2695. response.writeHead(200, {
  2696. "content-length": String(body.byteLength),
  2697. "content-type": "application/zip",
  2698. });
  2699. response.end(body);
  2700. });
  2701. await new Promise<void>((resolveListen) => {
  2702. server.listen(0, "127.0.0.1", resolveListen);
  2703. });
  2704. const address = server.address();
  2705. if (!address || typeof address === "string") {
  2706. throw new Error("zip fixture server did not bind to a TCP port");
  2707. }
  2708. return { baseUrl: `http://127.0.0.1:${address.port}`, server };
  2709. }
  2710. async function closeServer(server: Server | undefined): Promise<void> {
  2711. if (!server || !server.listening) return;
  2712. await new Promise<void>((resolveClose, rejectClose) => {
  2713. server.close((error) => {
  2714. if (error) rejectClose(error);
  2715. else resolveClose();
  2716. });
  2717. });
  2718. }
  2719. function createStoredZip(entries: Array<{ content?: string; path: string }>): Buffer {
  2720. const localParts: Buffer[] = [];
  2721. const centralParts: Buffer[] = [];
  2722. let offset = 0;
  2723. for (const entry of entries) {
  2724. const name = Buffer.from(entry.path);
  2725. const data = Buffer.from(entry.content ?? "");
  2726. const crc = crc32(data);
  2727. const local = Buffer.alloc(30);
  2728. local.writeUInt32LE(0x04034b50, 0);
  2729. local.writeUInt16LE(20, 4);
  2730. local.writeUInt16LE(0, 6);
  2731. local.writeUInt16LE(0, 8);
  2732. local.writeUInt16LE(0, 10);
  2733. local.writeUInt16LE(0, 12);
  2734. local.writeUInt32LE(crc, 14);
  2735. local.writeUInt32LE(data.byteLength, 18);
  2736. local.writeUInt32LE(data.byteLength, 22);
  2737. local.writeUInt16LE(name.byteLength, 26);
  2738. local.writeUInt16LE(0, 28);
  2739. localParts.push(local, name, data);
  2740. const central = Buffer.alloc(46);
  2741. central.writeUInt32LE(0x02014b50, 0);
  2742. central.writeUInt16LE(20, 4);
  2743. central.writeUInt16LE(20, 6);
  2744. central.writeUInt16LE(0, 8);
  2745. central.writeUInt16LE(0, 10);
  2746. central.writeUInt16LE(0, 12);
  2747. central.writeUInt16LE(0, 14);
  2748. central.writeUInt32LE(crc, 16);
  2749. central.writeUInt32LE(data.byteLength, 20);
  2750. central.writeUInt32LE(data.byteLength, 24);
  2751. central.writeUInt16LE(name.byteLength, 28);
  2752. central.writeUInt16LE(0, 30);
  2753. central.writeUInt16LE(0, 32);
  2754. central.writeUInt16LE(0, 34);
  2755. central.writeUInt16LE(0, 36);
  2756. central.writeUInt32LE((entry.path.endsWith("/") ? 0o040755 : 0o100644) * 0x10000, 38);
  2757. central.writeUInt32LE(offset, 42);
  2758. centralParts.push(central, name);
  2759. offset += local.byteLength + name.byteLength + data.byteLength;
  2760. }
  2761. const centralDirectory = Buffer.concat(centralParts);
  2762. const end = Buffer.alloc(22);
  2763. end.writeUInt32LE(0x06054b50, 0);
  2764. end.writeUInt16LE(0, 4);
  2765. end.writeUInt16LE(0, 6);
  2766. end.writeUInt16LE(entries.length, 8);
  2767. end.writeUInt16LE(entries.length, 10);
  2768. end.writeUInt32LE(centralDirectory.byteLength, 12);
  2769. end.writeUInt32LE(offset, 16);
  2770. end.writeUInt16LE(0, 20);
  2771. return Buffer.concat([...localParts, centralDirectory, end]);
  2772. }
  2773. const CRC32_TABLE = Array.from({ length: 256 }, (_, index) => {
  2774. let value = index;
  2775. for (let bit = 0; bit < 8; bit += 1) {
  2776. value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
  2777. }
  2778. return value >>> 0;
  2779. });
  2780. function crc32(buffer: Buffer): number {
  2781. let crc = 0xffffffff;
  2782. for (const byte of buffer) {
  2783. crc = CRC32_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);
  2784. }
  2785. return (crc ^ 0xffffffff) >>> 0;
  2786. }
  2787. async function writeTestFile(path: string, contents: string): Promise<void> {
  2788. await mkdir(dirname(path), { recursive: true });
  2789. await writeFile(path, contents);
  2790. }
  2791. async function writeExecutableTestFile(path: string, contents: string): Promise<void> {
  2792. await mkdir(dirname(path), { recursive: true });
  2793. await writeFile(path, contents, { mode: 0o755 });
  2794. }
  2795. async function writeKnownMarketplaces(
  2796. storageRoot: string,
  2797. marketplaces: Array<Record<string, unknown>>,
  2798. ): Promise<void> {
  2799. await writeTestFile(
  2800. join(storageRoot, "known_marketplaces.json"),
  2801. JSON.stringify({ version: 1, marketplaces }),
  2802. );
  2803. }
  2804. function hashBytes(bytes: Buffer): string {
  2805. return createHash("sha256").update(bytes).digest("hex");
  2806. }