plugins.test.ts 93 KB

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