plugins.test.ts 95 KB

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