plugins.test.ts 105 KB

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