plugins.test.ts 91 KB

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