config.test.ts 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  1. import { describe, expect, it } from "vitest";
  2. import { createConfig, updateUiLocaleInFileConfig } from "../src/config/index.js";
  3. import { parseEnvConfig } from "../src/config/env-config.adapter.js";
  4. import {
  5. addSuppressedBuiltinInFileConfig,
  6. loadFileConfig,
  7. removePluginFromFileConfig,
  8. removeSuppressedBuiltinInFileConfig,
  9. updatePluginEnabledInFileConfig,
  10. updatePluginOptionsInFileConfig,
  11. } from "../src/config/file-config.adapter.js";
  12. import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
  13. import { tmpdir } from "node:os";
  14. import { join } from "node:path";
  15. describe("config adapters", () => {
  16. it("migrates the legacy official CUA plugin id to the canonical id", async () => {
  17. const dir = await mkdtemp(join(tmpdir(), "zcode-config-cua-identity-"));
  18. const configPath = join(dir, "config.json");
  19. try {
  20. await writeFile(
  21. configPath,
  22. JSON.stringify({
  23. plugins: {
  24. enabledPlugins: {
  25. "zcode-cua@zcode-plugins-official": true,
  26. "computer-use@zcode-plugins-official": false,
  27. },
  28. suppressedBuiltins: [
  29. "zcode-cua@zcode-plugins-official",
  30. "computer-use@zcode-plugins-official",
  31. ],
  32. options: {
  33. "zcode-cua@zcode-plugins-official": { apiKey: "legacy-key" },
  34. "computer-use@zcode-plugins-official": { apiKey: "canonical-key" },
  35. },
  36. },
  37. }),
  38. );
  39. const loaded = loadFileConfig(configPath);
  40. expect(loaded.config.plugins?.enabledPlugins).toEqual({
  41. "computer-use@zcode-plugins-official": false,
  42. });
  43. expect(loaded.config.plugins?.suppressedBuiltins).toEqual([
  44. "computer-use@zcode-plugins-official",
  45. ]);
  46. expect(loaded.config.plugins?.options).toEqual({
  47. "computer-use@zcode-plugins-official": { apiKey: "canonical-key" },
  48. });
  49. } finally {
  50. await rm(dir, { force: true, recursive: true });
  51. }
  52. });
  53. it("persists the canonical CUA plugin id while loading legacy config", async () => {
  54. const dir = await mkdtemp(join(tmpdir(), "zcode-config-cua-writeback-"));
  55. const path = join(dir, "config.json");
  56. await writeFile(
  57. path,
  58. JSON.stringify({
  59. plugins: {
  60. enabledPlugins: { "zcode-cua@zcode-plugins-official": true },
  61. suppressedBuiltins: ["zcode-cua@zcode-plugins-official"],
  62. options: {
  63. "zcode-cua@zcode-plugins-official": { apiKey: "legacy-key" },
  64. },
  65. },
  66. }),
  67. );
  68. loadFileConfig(path);
  69. expect(JSON.parse(await readFile(path, "utf8"))).toEqual({
  70. plugins: {
  71. enabledPlugins: { "computer-use@zcode-plugins-official": true },
  72. suppressedBuiltins: ["computer-use@zcode-plugins-official"],
  73. options: {
  74. "computer-use@zcode-plugins-official": { apiKey: "legacy-key" },
  75. },
  76. },
  77. });
  78. await rm(dir, { recursive: true, force: true });
  79. });
  80. it("writes canonical CUA ids when removing legacy config entries", async () => {
  81. const dir = await mkdtemp(join(tmpdir(), "zcode-config-cua-write-migration-"));
  82. const configPath = join(dir, "config.json");
  83. try {
  84. await writeFile(
  85. configPath,
  86. JSON.stringify({
  87. plugins: {
  88. enabledPlugins: { "zcode-cua@zcode-plugins-official": true },
  89. suppressedBuiltins: ["zcode-cua@zcode-plugins-official"],
  90. },
  91. }),
  92. );
  93. expect(
  94. (
  95. await removeSuppressedBuiltinInFileConfig(
  96. configPath,
  97. "computer-use@zcode-plugins-official",
  98. )
  99. ).suppressed,
  100. ).toBe(false);
  101. expect(
  102. (await removePluginFromFileConfig(configPath, "computer-use@zcode-plugins-official"))
  103. .removedEnabled,
  104. ).toBe(true);
  105. expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual({
  106. plugins: { enabledPlugins: {}, suppressedBuiltins: [], options: {} },
  107. });
  108. } finally {
  109. await rm(dir, { force: true, recursive: true });
  110. }
  111. });
  112. it("clears only explicitly selected Plugin option keys", async () => {
  113. const dir = await mkdtemp(join(tmpdir(), "zcode-config-plugin-option-clear-"));
  114. const configPath = join(dir, "config.json");
  115. const pluginId = "secret-plugin@fixture";
  116. try {
  117. await writeFile(
  118. configPath,
  119. JSON.stringify({
  120. plugins: {
  121. enabledPlugins: { [pluginId]: true },
  122. options: {
  123. [pluginId]: {
  124. token: "secret",
  125. region: "us-east-1",
  126. },
  127. },
  128. },
  129. }),
  130. );
  131. await updatePluginOptionsInFileConfig(configPath, pluginId, { region: "eu-west-1" }, [
  132. "token",
  133. ]);
  134. expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual({
  135. plugins: {
  136. enabledPlugins: { [pluginId]: true },
  137. options: {
  138. [pluginId]: {
  139. region: "eu-west-1",
  140. },
  141. },
  142. },
  143. });
  144. } finally {
  145. await rm(dir, { force: true, recursive: true });
  146. }
  147. });
  148. it("deep merges Workspace Plugin enablement and options over User config", async () => {
  149. const dir = await mkdtemp(join(tmpdir(), "zcode-config-workspace-plugins-"));
  150. const userPath = join(dir, "user.json");
  151. const workspacePath = join(dir, ".zcode", "config.json");
  152. try {
  153. await mkdir(join(dir, ".zcode"), { recursive: true });
  154. await writeFile(
  155. userPath,
  156. JSON.stringify({
  157. plugins: {
  158. dirs: [join(dir, "user-plugin")],
  159. enabledPlugins: {
  160. "workspace-plugin@fixture": true,
  161. "user-only@fixture": true,
  162. },
  163. options: {
  164. "workspace-plugin@fixture": {
  165. inherited: "user",
  166. overridden: "user",
  167. },
  168. },
  169. },
  170. }),
  171. );
  172. await writeFile(
  173. workspacePath,
  174. JSON.stringify({
  175. plugins: {
  176. enabledPlugins: {
  177. "workspace-plugin@fixture": false,
  178. },
  179. options: {
  180. "workspace-plugin@fixture": {
  181. overridden: "workspace",
  182. workspaceOnly: true,
  183. },
  184. },
  185. },
  186. }),
  187. );
  188. const result = createConfig({
  189. env: {},
  190. userConfigPath: userPath,
  191. projectConfigPath: workspacePath,
  192. workingDirectory: dir,
  193. });
  194. expect(result.config.plugins.enabledPlugins).toEqual({
  195. "workspace-plugin@fixture": false,
  196. "user-only@fixture": true,
  197. });
  198. expect(result.config.plugins.options).toEqual({
  199. "workspace-plugin@fixture": {
  200. inherited: "user",
  201. overridden: "workspace",
  202. workspaceOnly: true,
  203. },
  204. });
  205. expect(result.sources.project.paths).toEqual([workspacePath]);
  206. expect(result.sources.plugins.enabled).toEqual({
  207. "user-only@fixture": "user",
  208. "workspace-plugin@fixture": "workspace",
  209. });
  210. expect(result.sources.plugins.dirs).toEqual({
  211. user: [join(dir, "user-plugin")],
  212. workspace: [],
  213. });
  214. expect(result.config.plugins.dirs).toEqual([join(dir, "user-plugin")]);
  215. expect(result.sources.plugins.options).toEqual({
  216. "workspace-plugin@fixture": {
  217. inherited: "user",
  218. overridden: "workspace",
  219. workspaceOnly: "workspace",
  220. },
  221. });
  222. } finally {
  223. await rm(dir, { force: true, recursive: true });
  224. }
  225. });
  226. it("keeps Marketplace declarations in the User config layer", async () => {
  227. const dir = await mkdtemp(join(tmpdir(), "zcode-config-workspace-marketplaces-"));
  228. const userPath = join(dir, "user.json");
  229. const workspacePath = join(dir, "workspace.json");
  230. try {
  231. await writeFile(
  232. userPath,
  233. JSON.stringify({
  234. plugins: {
  235. extraKnownMarketplaces: {
  236. "shared-market": {
  237. source: { source: "github", repo: "example/user-market" },
  238. },
  239. "user-market": {
  240. source: { source: "url", url: "https://example.test/user-market.json" },
  241. },
  242. },
  243. },
  244. }),
  245. );
  246. await writeFile(
  247. workspacePath,
  248. JSON.stringify({
  249. plugins: {
  250. extraKnownMarketplaces: {
  251. "shared-market": {
  252. source: { source: "directory", path: "./workspace-market" },
  253. },
  254. "workspace-market": {
  255. source: { source: "file", path: "./workspace-market.json" },
  256. },
  257. },
  258. },
  259. }),
  260. );
  261. const result = createConfig({
  262. env: {},
  263. userConfigPath: userPath,
  264. projectConfigPath: workspacePath,
  265. });
  266. expect(result.config.plugins.extraKnownMarketplaces).toEqual({
  267. "shared-market": {
  268. source: { source: "github", repo: "example/user-market" },
  269. },
  270. "user-market": {
  271. source: { source: "url", url: "https://example.test/user-market.json" },
  272. },
  273. });
  274. expect(result.sources.plugins.marketplaces).toEqual({
  275. "shared-market": "user",
  276. "user-market": "user",
  277. });
  278. } finally {
  279. await rm(dir, { force: true, recursive: true });
  280. }
  281. });
  282. it("parses the supported ZCODE environment surface", () => {
  283. const config = parseEnvConfig({
  284. ZCODE_STORAGE_DIR: "/tmp/zcode",
  285. ZCODE_HTTP_PROXY: "http://127.0.0.1:7890",
  286. ZCODE_NO_PROXY: "localhost,127.0.0.1",
  287. ZCODE_AGENT_CA_CERT: "/tmp/zcode-ca.pem",
  288. ZCODE_HTTP_TIMEOUT: "1234",
  289. ZCODE_LOCALE: "zh-CN",
  290. ZCODE_LOG_FORMAT: "json",
  291. });
  292. expect(config.model).toBeUndefined();
  293. expect(config.storage?.dir).toBe("/tmp/zcode");
  294. expect(config.network?.httpProxy).toBe("http://127.0.0.1:7890");
  295. expect(config.network?.noProxy).toBe("localhost,127.0.0.1");
  296. expect(config.network?.caCertFile).toBe("/tmp/zcode-ca.pem");
  297. expect(config.network?.timeout).toBe(1234);
  298. expect(config.ui).toBeUndefined();
  299. expect(config.logging?.format).toBe("json");
  300. expect(config.logging?.level).toBeUndefined();
  301. });
  302. it("loads the supported memory config fields", async () => {
  303. const dir = await mkdtemp(join(tmpdir(), "zcode-config-memory-"));
  304. const path = join(dir, "config.json");
  305. try {
  306. await writeFile(
  307. path,
  308. JSON.stringify({
  309. memory: {
  310. use: false,
  311. },
  312. }),
  313. );
  314. const loaded = loadFileConfig(path);
  315. const merged = createConfig({ env: {}, userConfigPath: path });
  316. expect(loaded.loaded).toBe(true);
  317. expect(loaded.config.memory).toEqual({
  318. use: false,
  319. });
  320. expect(merged.config.memory).toEqual({
  321. use: false,
  322. });
  323. } finally {
  324. await rm(dir, { force: true, recursive: true });
  325. }
  326. });
  327. it("parses session database path environment overrides", () => {
  328. expect(
  329. parseEnvConfig({
  330. ZCODE_SESSION_DB_PATH: "/tmp/zcode/db/db.sqlite",
  331. }).storage?.sessionDbPath,
  332. ).toBe("/tmp/zcode/db/db.sqlite");
  333. expect(
  334. parseEnvConfig({
  335. ZCODE_SESSION_DB: "/tmp/zcode/legacy.sqlite",
  336. }).storage?.sessionDbPath,
  337. ).toBe("/tmp/zcode/legacy.sqlite");
  338. });
  339. it("loads no-proxy rules from file config", async () => {
  340. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  341. const path = join(dir, "config.json");
  342. try {
  343. await writeFile(
  344. path,
  345. JSON.stringify({
  346. network: {
  347. httpProxy: "http://127.0.0.1:7890",
  348. noProxy: "localhost,127.0.0.1",
  349. caCertFile: "/tmp/zcode-ca.pem",
  350. },
  351. }),
  352. );
  353. const merged = createConfig({ env: {}, userConfigPath: path });
  354. expect(merged.config.network.httpProxy).toBe("http://127.0.0.1:7890");
  355. expect(merged.config.network.noProxy).toBe("localhost,127.0.0.1");
  356. expect(merged.config.network.caCertFile).toBe("/tmp/zcode-ca.pem");
  357. } finally {
  358. await rm(dir, { force: true, recursive: true });
  359. }
  360. });
  361. it("ignores undeclared ZCODE environment switches", () => {
  362. const config = parseEnvConfig({
  363. ZCODE_LOG_LEVEL: "debug",
  364. ZCODE_UNDECLARED_FLAG: "1",
  365. });
  366. expect(config).toEqual({});
  367. });
  368. it("loads yolo mode from file config", async () => {
  369. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  370. const path = join(dir, "config.json");
  371. try {
  372. await writeFile(path, JSON.stringify({ permission: { mode: "yolo" } }));
  373. const result = loadFileConfig(path);
  374. expect(result.loaded).toBe(true);
  375. expect(result.config.permission?.mode).toBe("yolo");
  376. } finally {
  377. await rm(dir, { force: true, recursive: true });
  378. }
  379. });
  380. it("loads edit mode from file config", async () => {
  381. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  382. const path = join(dir, "config.json");
  383. try {
  384. await writeFile(path, JSON.stringify({ permission: { mode: "edit" } }));
  385. const result = loadFileConfig(path);
  386. expect(result.loaded).toBe(true);
  387. expect(result.config.permission?.mode).toBe("edit");
  388. } finally {
  389. await rm(dir, { force: true, recursive: true });
  390. }
  391. });
  392. it("loads skill/command enable overrides from file config", async () => {
  393. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  394. const path = join(dir, "config.json");
  395. try {
  396. await writeFile(
  397. path,
  398. JSON.stringify({
  399. skill: { "/abs/skills/demo/SKILL.md": { enable: false } },
  400. command: { "/abs/commands/demo.md": { enable: false } },
  401. }),
  402. );
  403. const result = loadFileConfig(path);
  404. const merged = createConfig({ env: {}, userConfigPath: path });
  405. expect(result.loaded).toBe(true);
  406. // JSON 的 skill/command 字段映射到 runtime 的 skillOverrides/commandOverrides
  407. expect(result.config.skillOverrides?.["/abs/skills/demo/SKILL.md"]?.enable).toBe(false);
  408. expect(result.config.commandOverrides?.["/abs/commands/demo.md"]?.enable).toBe(false);
  409. expect(merged.config.skillOverrides["/abs/skills/demo/SKILL.md"]?.enable).toBe(false);
  410. expect(merged.config.commandOverrides["/abs/commands/demo.md"]?.enable).toBe(false);
  411. } finally {
  412. await rm(dir, { force: true, recursive: true });
  413. }
  414. });
  415. it("parses plugins.suppressedBuiltins as a string array", async () => {
  416. const dir = await mkdtemp(join(tmpdir(), "zcode-config-suppressed-"));
  417. const path = join(dir, "config.json");
  418. await writeFile(
  419. path,
  420. JSON.stringify({ plugins: { suppressedBuiltins: ["skill-creator@zcode-plugins-official"] } }),
  421. );
  422. const loaded = loadFileConfig(path);
  423. expect(loaded.config.plugins.suppressedBuiltins).toEqual([
  424. "skill-creator@zcode-plugins-official",
  425. ]);
  426. });
  427. it("maps skills path enable entries to skill overrides", async () => {
  428. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  429. const path = join(dir, "config.json");
  430. try {
  431. await writeFile(
  432. path,
  433. JSON.stringify({
  434. skills: {
  435. enabled: true,
  436. roots: ["/abs/skills"],
  437. "/abs/skills/disabled/SKILL.md": { enable: false },
  438. "/abs/skills/enabled/SKILL.md": { enable: true },
  439. },
  440. }),
  441. );
  442. const result = loadFileConfig(path);
  443. const merged = createConfig({ env: {}, userConfigPath: path });
  444. expect(result.loaded).toBe(true);
  445. expect(result.config.skills).toEqual({
  446. enabled: true,
  447. roots: ["/abs/skills"],
  448. });
  449. expect(result.config.skillOverrides?.["/abs/skills/disabled/SKILL.md"]?.enable).toBe(false);
  450. expect(result.config.skillOverrides?.["/abs/skills/enabled/SKILL.md"]?.enable).toBe(true);
  451. expect(merged.config.skillOverrides["/abs/skills/disabled/SKILL.md"]?.enable).toBe(false);
  452. expect(merged.config.skillOverrides["/abs/skills/enabled/SKILL.md"]?.enable).toBe(true);
  453. } finally {
  454. await rm(dir, { force: true, recursive: true });
  455. }
  456. });
  457. it("loads top-level skills config from file config", async () => {
  458. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  459. const path = join(dir, "config.json");
  460. try {
  461. await writeFile(
  462. path,
  463. JSON.stringify({
  464. skills: {
  465. enabled: false,
  466. includeInstructions: false,
  467. metadataBudget: 1024,
  468. roots: ["/abs/skills"],
  469. },
  470. }),
  471. );
  472. const result = loadFileConfig(path);
  473. const merged = createConfig({ env: {}, userConfigPath: path });
  474. expect(result.loaded).toBe(true);
  475. expect(result.config.skills).toEqual({
  476. enabled: false,
  477. includeInstructions: false,
  478. metadataBudget: 1024,
  479. roots: ["/abs/skills"],
  480. });
  481. expect(merged.config.skills.enabled).toBe(false);
  482. expect(merged.config.skills.includeInstructions).toBe(false);
  483. expect(merged.config.skills.metadataBudget).toBe(1024);
  484. expect(merged.config.skills.roots).toEqual(["/abs/skills"]);
  485. } finally {
  486. await rm(dir, { force: true, recursive: true });
  487. }
  488. });
  489. it("loads UI locale from file config", async () => {
  490. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  491. const path = join(dir, "config.json");
  492. try {
  493. await writeFile(path, JSON.stringify({ ui: { locale: "zh-CN" } }));
  494. const result = loadFileConfig(path);
  495. const merged = createConfig({ env: {}, userConfigPath: path });
  496. expect(result.loaded).toBe(true);
  497. expect(result.config.ui?.locale).toBe("zh-CN");
  498. expect(merged.config.ui.locale).toBe("zh-CN");
  499. } finally {
  500. await rm(dir, { force: true, recursive: true });
  501. }
  502. });
  503. it("loads auto UI locale from file config", async () => {
  504. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  505. const path = join(dir, "config.json");
  506. try {
  507. await writeFile(path, JSON.stringify({ ui: { locale: "auto" } }));
  508. const result = loadFileConfig(path);
  509. const merged = createConfig({ env: {}, userConfigPath: path });
  510. expect(result.loaded).toBe(true);
  511. expect(result.config.ui?.locale).toBe("auto");
  512. expect(merged.config.ui.locale).toBe("auto");
  513. } finally {
  514. await rm(dir, { force: true, recursive: true });
  515. }
  516. });
  517. it("loads UI theme from file config", async () => {
  518. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  519. const path = join(dir, "config.json");
  520. try {
  521. await writeFile(path, JSON.stringify({ ui: { theme: "light" } }));
  522. const result = loadFileConfig(path);
  523. const merged = createConfig({ env: {}, userConfigPath: path });
  524. expect(result.loaded).toBe(true);
  525. expect(result.config.ui?.theme).toBe("light");
  526. expect(merged.config.ui.theme).toBe("light");
  527. } finally {
  528. await rm(dir, { force: true, recursive: true });
  529. }
  530. });
  531. it("rejects unsupported UI theme values from file config", async () => {
  532. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  533. const path = join(dir, "config.json");
  534. try {
  535. await writeFile(path, JSON.stringify({ ui: { theme: "sepia" } }));
  536. const result = loadFileConfig(path);
  537. expect(result.loaded).toBe(false);
  538. expect(result.config.ui).toBeUndefined();
  539. } finally {
  540. await rm(dir, { force: true, recursive: true });
  541. }
  542. });
  543. it("patches UI locale while preserving unrelated config fields", async () => {
  544. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  545. const path = join(dir, "config.json");
  546. try {
  547. await writeFile(
  548. path,
  549. JSON.stringify({
  550. model: {
  551. main: "openai/gpt-5.1",
  552. },
  553. permission: {
  554. mode: "plan",
  555. },
  556. ui: {
  557. density: "compact",
  558. locale: "en-US",
  559. },
  560. }),
  561. );
  562. const result = await updateUiLocaleInFileConfig(path, "zh-CN");
  563. const written = JSON.parse(await readFile(path, "utf-8"));
  564. expect(result).toEqual({
  565. locale: "zh-CN",
  566. path,
  567. });
  568. expect(written).toMatchObject({
  569. model: {
  570. main: "openai/gpt-5.1",
  571. },
  572. permission: {
  573. mode: "plan",
  574. },
  575. ui: {
  576. density: "compact",
  577. locale: "zh-CN",
  578. },
  579. });
  580. } finally {
  581. await rm(dir, { force: true, recursive: true });
  582. }
  583. });
  584. it("creates config files when patching UI locale", async () => {
  585. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  586. const path = join(dir, "nested", "config.json");
  587. try {
  588. await updateUiLocaleInFileConfig(path, "auto");
  589. const written = JSON.parse(await readFile(path, "utf-8"));
  590. expect(written).toEqual({
  591. ui: {
  592. locale: "auto",
  593. },
  594. });
  595. } finally {
  596. await rm(dir, { force: true, recursive: true });
  597. }
  598. });
  599. it("rejects unsupported UI locale values from file config", async () => {
  600. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  601. const path = join(dir, "config.json");
  602. try {
  603. await writeFile(path, JSON.stringify({ ui: { locale: "fr-FR" } }));
  604. const result = loadFileConfig(path);
  605. expect(result.loaded).toBe(false);
  606. expect(result.config.ui).toBeUndefined();
  607. } finally {
  608. await rm(dir, { force: true, recursive: true });
  609. }
  610. });
  611. it("loads MCP server config from file config", async () => {
  612. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  613. const path = join(dir, "config.json");
  614. try {
  615. await writeFile(
  616. path,
  617. JSON.stringify({
  618. features: {
  619. mcp: true,
  620. },
  621. mcp: {
  622. servers: {
  623. local: {
  624. type: "stdio",
  625. command: "node",
  626. args: ["server.js"],
  627. cwd: ".",
  628. env: {
  629. EXAMPLE: "1",
  630. },
  631. },
  632. remote: {
  633. type: "http",
  634. url: "https://example.com/mcp",
  635. headers: {
  636. Authorization: "Bearer token",
  637. },
  638. oauth: {
  639. type: "client_credentials",
  640. clientId: "zcode-client",
  641. clientSecret: "secret",
  642. scope: "mcp:tools",
  643. },
  644. timeoutMs: 30000,
  645. },
  646. events: {
  647. type: "sse",
  648. url: "https://example.com/sse",
  649. oauth: {
  650. type: "authorization_code",
  651. clientName: "ZCode",
  652. redirectPath: "/oauth/callback/mcp/figma",
  653. scope: "mcp:connect",
  654. },
  655. enabled: false,
  656. },
  657. },
  658. },
  659. }),
  660. );
  661. const result = loadFileConfig(path);
  662. expect(result.loaded).toBe(true);
  663. expect(result.config.features?.mcp).toBe(true);
  664. expect(result.config.mcp?.servers?.local).toMatchObject({
  665. type: "stdio",
  666. command: "node",
  667. args: ["server.js"],
  668. });
  669. expect(result.config.mcp?.servers?.remote).toMatchObject({
  670. type: "http",
  671. url: "https://example.com/mcp",
  672. oauth: {
  673. type: "client_credentials",
  674. clientId: "zcode-client",
  675. clientSecret: "secret",
  676. scope: "mcp:tools",
  677. },
  678. timeoutMs: 30000,
  679. });
  680. expect(result.config.mcp?.servers?.events).toMatchObject({
  681. type: "sse",
  682. oauth: {
  683. type: "authorization_code",
  684. clientName: "ZCode",
  685. redirectPath: "/oauth/callback/mcp/figma",
  686. scope: "mcp:connect",
  687. },
  688. enabled: false,
  689. });
  690. } finally {
  691. await rm(dir, { force: true, recursive: true });
  692. }
  693. });
  694. it("keeps an MCP server disabled when legacy enable:false coexists with enabled:true", async () => {
  695. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  696. const path = join(dir, "config.json");
  697. try {
  698. await writeFile(
  699. path,
  700. JSON.stringify({
  701. mcp: {
  702. servers: {
  703. // 桌面端「停用」写入 enable:false,而外部导入/手工编辑的同一条配置里
  704. // 已经带着 enabled:true。禁用意图必须胜出。
  705. playwright: {
  706. type: "stdio",
  707. command: "npx",
  708. args: ["-y", "@playwright/mcp@latest"],
  709. enable: false,
  710. enabled: true,
  711. },
  712. },
  713. },
  714. }),
  715. );
  716. const result = loadFileConfig(path);
  717. expect(result.config.mcp?.servers?.playwright?.enabled).toBe(false);
  718. } finally {
  719. await rm(dir, { force: true, recursive: true });
  720. }
  721. });
  722. it("keeps an MCP server disabled when enabled:false coexists with legacy enable:true", async () => {
  723. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  724. const path = join(dir, "config.json");
  725. try {
  726. await writeFile(
  727. path,
  728. JSON.stringify({
  729. mcp: {
  730. servers: {
  731. playwright: {
  732. type: "stdio",
  733. command: "npx",
  734. args: ["-y", "@playwright/mcp@latest"],
  735. enable: true,
  736. enabled: false,
  737. },
  738. },
  739. },
  740. }),
  741. );
  742. const result = loadFileConfig(path);
  743. expect(result.config.mcp?.servers?.playwright?.enabled).toBe(false);
  744. } finally {
  745. await rm(dir, { force: true, recursive: true });
  746. }
  747. });
  748. it("keeps an MCP server enabled when both enable and enabled are true", async () => {
  749. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  750. const path = join(dir, "config.json");
  751. try {
  752. await writeFile(
  753. path,
  754. JSON.stringify({
  755. mcp: {
  756. servers: {
  757. playwright: {
  758. type: "stdio",
  759. command: "npx",
  760. args: ["-y", "@playwright/mcp@latest"],
  761. enable: true,
  762. enabled: true,
  763. },
  764. },
  765. },
  766. }),
  767. );
  768. const result = loadFileConfig(path);
  769. expect(result.config.mcp?.servers?.playwright?.enabled).toBe(true);
  770. } finally {
  771. await rm(dir, { force: true, recursive: true });
  772. }
  773. });
  774. it("preserves fresh HTTP MCP config without writing implicit OAuth", async () => {
  775. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  776. const path = join(dir, "config.json");
  777. try {
  778. await writeFile(
  779. path,
  780. JSON.stringify({
  781. mcp: {
  782. servers: {
  783. notion: {
  784. type: "http",
  785. url: "https://mcp.notion.com/mcp",
  786. timeoutMs: 30000,
  787. },
  788. },
  789. },
  790. }),
  791. );
  792. const result = loadFileConfig(path);
  793. expect(result.loaded).toBe(true);
  794. expect(result.config.mcp?.servers?.notion).toMatchObject({
  795. type: "http",
  796. url: "https://mcp.notion.com/mcp",
  797. timeoutMs: 30000,
  798. });
  799. expect(result.config.mcp?.servers?.notion?.oauth).toBeUndefined();
  800. } finally {
  801. await rm(dir, { force: true, recursive: true });
  802. }
  803. });
  804. it("skips invalid MCP OAuth config without dropping unrelated config", async () => {
  805. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  806. const path = join(dir, "config.json");
  807. try {
  808. await writeFile(
  809. path,
  810. JSON.stringify({
  811. mcp: {
  812. servers: {
  813. broken: {
  814. type: "http",
  815. url: "https://example.com/mcp",
  816. oauth: {
  817. type: "client_credentials",
  818. clientId: "zcode-client",
  819. },
  820. },
  821. },
  822. },
  823. plugins: {
  824. enabled: true,
  825. },
  826. }),
  827. );
  828. const result = loadFileConfig(path);
  829. expect(result.loaded).toBe(true);
  830. expect(result.config.mcp?.servers).not.toHaveProperty("broken");
  831. expect(result.config.plugins?.enabled).toBe(true);
  832. expect(result.diagnostics).toEqual([
  833. expect.objectContaining({
  834. code: "config_mcp_server_invalid",
  835. path: "mcp.servers.broken",
  836. severity: "warning",
  837. }),
  838. ]);
  839. } finally {
  840. await rm(dir, { force: true, recursive: true });
  841. }
  842. });
  843. it("normalizes app-managed MCP config aliases from file config", async () => {
  844. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  845. const path = join(dir, "config.json");
  846. try {
  847. await writeFile(
  848. path,
  849. JSON.stringify({
  850. mcp: {
  851. servers: {
  852. "figma-dev-mode-mcp-server": {
  853. type: "stdio",
  854. command: "npx",
  855. args: ["-y", "figma-developer-mcp"],
  856. enable: false,
  857. },
  858. "chrome-devtools": {
  859. command: "npx",
  860. args: ["-y", "chrome-devtools-mcp@latest"],
  861. },
  862. node_repl: {
  863. command: "/opt/tools/node_repl",
  864. args: [],
  865. timeout: 30,
  866. startup_timeout_sec: 120,
  867. },
  868. },
  869. },
  870. }),
  871. );
  872. const result = loadFileConfig(path);
  873. expect(result.loaded).toBe(true);
  874. expect(result.config.mcp?.servers?.["figma-dev-mode-mcp-server"]).toMatchObject({
  875. type: "stdio",
  876. command: "npx",
  877. enabled: false,
  878. });
  879. expect(result.config.mcp?.servers?.["figma-dev-mode-mcp-server"]).not.toHaveProperty(
  880. "enable",
  881. );
  882. expect(result.config.mcp?.servers?.["chrome-devtools"]).toMatchObject({
  883. type: "stdio",
  884. command: "npx",
  885. args: ["-y", "chrome-devtools-mcp@latest"],
  886. });
  887. expect(result.config.mcp?.servers?.node_repl).toMatchObject({
  888. type: "stdio",
  889. command: "/opt/tools/node_repl",
  890. });
  891. expect(result.config.mcp?.servers?.node_repl).not.toHaveProperty("timeout");
  892. expect(result.config.mcp?.servers?.node_repl).not.toHaveProperty("startup_timeout_sec");
  893. } finally {
  894. await rm(dir, { force: true, recursive: true });
  895. }
  896. });
  897. it("normalizes legacy MCP http_headers to runtime headers", async () => {
  898. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  899. const path = join(dir, "config.json");
  900. try {
  901. await writeFile(
  902. path,
  903. JSON.stringify({
  904. mcp: {
  905. servers: {
  906. web_search_prime: {
  907. type: "http",
  908. url: "https://bigmodel.example.test/mcp",
  909. http_headers: {
  910. Authorization: "Bearer token",
  911. },
  912. },
  913. },
  914. },
  915. }),
  916. );
  917. const result = loadFileConfig(path);
  918. expect(result.loaded).toBe(true);
  919. expect(result.config.mcp?.servers?.web_search_prime).toMatchObject({
  920. type: "http",
  921. headers: {
  922. Authorization: "Bearer token",
  923. },
  924. });
  925. expect(result.config.mcp?.servers?.web_search_prime).not.toHaveProperty("http_headers");
  926. } finally {
  927. await rm(dir, { force: true, recursive: true });
  928. }
  929. });
  930. it("normalizes legacy MCP remote/environment fields without dropping plugins config", async () => {
  931. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  932. const path = join(dir, "config.json");
  933. try {
  934. await writeFile(
  935. path,
  936. JSON.stringify({
  937. mcp: {
  938. servers: {
  939. "GLM-Image-MCP": {
  940. enabled: true,
  941. environment: {
  942. Z_AI_API_KEY: "test-key",
  943. Z_AI_MODE: "ZHIPU",
  944. },
  945. command: "npx",
  946. args: ["-y", "@z_ai/mcp-server"],
  947. type: "stdio",
  948. },
  949. "GLM-WebReader-MCP": {
  950. enabled: true,
  951. headers: {
  952. Authorization: "Bearer token",
  953. },
  954. type: "remote",
  955. url: "https://open.bigmodel.cn/api/mcp/web_reader/mcp",
  956. },
  957. },
  958. },
  959. plugins: {
  960. enabledPlugins: {
  961. "superpowers@zcode-plugins-official": true,
  962. "skill-creator@zcode-plugins-official": false,
  963. },
  964. },
  965. }),
  966. );
  967. const result = loadFileConfig(path);
  968. const merged = createConfig({ env: {}, userConfigPath: path });
  969. expect(result.loaded).toBe(true);
  970. expect(result.diagnostics).toEqual([]);
  971. expect(result.config.mcp?.servers?.["GLM-Image-MCP"]).toMatchObject({
  972. type: "stdio",
  973. env: {
  974. Z_AI_API_KEY: "test-key",
  975. Z_AI_MODE: "ZHIPU",
  976. },
  977. });
  978. expect(result.config.mcp?.servers?.["GLM-Image-MCP"]).not.toHaveProperty("environment");
  979. expect(result.config.mcp?.servers?.["GLM-WebReader-MCP"]).toMatchObject({
  980. headers: {
  981. Authorization: "Bearer token",
  982. },
  983. type: "http",
  984. url: "https://open.bigmodel.cn/api/mcp/web_reader/mcp",
  985. });
  986. expect(merged.config.plugins.enabledPlugins).toMatchObject({
  987. "skill-creator@zcode-plugins-official": false,
  988. "superpowers@zcode-plugins-official": true,
  989. });
  990. } finally {
  991. await rm(dir, { force: true, recursive: true });
  992. }
  993. });
  994. it("keeps non-MCP config when one MCP server is invalid", async () => {
  995. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  996. const logDir = join(dir, "log");
  997. const path = join(dir, "config.json");
  998. try {
  999. await writeFile(
  1000. path,
  1001. JSON.stringify({
  1002. mcp: {
  1003. servers: {
  1004. valid: {
  1005. type: "remote",
  1006. url: "https://example.com/mcp",
  1007. },
  1008. broken: {
  1009. type: "stdio",
  1010. args: ["server.js"],
  1011. },
  1012. },
  1013. },
  1014. plugins: {
  1015. enabledPlugins: {
  1016. "android-emulator@zcode-plugins-official": true,
  1017. },
  1018. },
  1019. }),
  1020. );
  1021. const result = loadFileConfig(path);
  1022. const merged = createConfig({
  1023. env: { ZCODE_LOG_DIR: logDir },
  1024. userConfigPath: path,
  1025. });
  1026. expect(result.loaded).toBe(true);
  1027. expect(result.config.mcp?.servers?.valid).toMatchObject({
  1028. type: "http",
  1029. url: "https://example.com/mcp",
  1030. });
  1031. expect(result.config.mcp?.servers).not.toHaveProperty("broken");
  1032. expect(
  1033. result.config.plugins?.enabledPlugins?.["android-emulator@zcode-plugins-official"],
  1034. ).toBe(true);
  1035. expect(result.diagnostics).toEqual([
  1036. expect.objectContaining({
  1037. code: "config_mcp_server_invalid",
  1038. path: "mcp.servers.broken",
  1039. severity: "warning",
  1040. }),
  1041. ]);
  1042. expect(merged.sources.user.diagnostics).toEqual(result.diagnostics);
  1043. expect(merged.config.plugins.enabledPlugins["android-emulator@zcode-plugins-official"]).toBe(
  1044. true,
  1045. );
  1046. await expect(readLogEntries(logDir)).resolves.toEqual([
  1047. expect.objectContaining({
  1048. event: "config.mcp_server.skipped",
  1049. level: "warn",
  1050. message: "MCP server config skipped",
  1051. module: "adapters.config",
  1052. context: expect.objectContaining({
  1053. configPath: path,
  1054. configScope: "user",
  1055. diagnosticCode: "config_mcp_server_invalid",
  1056. diagnosticPath: "mcp.servers.broken",
  1057. }),
  1058. }),
  1059. ]);
  1060. } finally {
  1061. await rm(dir, { force: true, recursive: true });
  1062. }
  1063. });
  1064. it("reports invalid discovered project config diagnostics", async () => {
  1065. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1066. const logDir = join(root, "log");
  1067. const projectConfigPath = join(root, "zcode.json");
  1068. try {
  1069. await mkdir(join(root, ".git"));
  1070. await writeFile(
  1071. projectConfigPath,
  1072. JSON.stringify({
  1073. ui: {
  1074. theme: "sepia",
  1075. },
  1076. }),
  1077. );
  1078. const result = createConfig({
  1079. env: { ZCODE_LOG_DIR: logDir },
  1080. skipUserConfig: true,
  1081. workingDirectory: root,
  1082. });
  1083. expect(result.sources.project.loaded).toBe(false);
  1084. expect(result.sources.project.diagnostics).toEqual([
  1085. expect.objectContaining({
  1086. code: "config_file_invalid",
  1087. message: expect.stringContaining("ui.theme: Invalid option: expected one of"),
  1088. severity: "error",
  1089. }),
  1090. ]);
  1091. await expect(readLogEntries(logDir)).resolves.toEqual([
  1092. expect.objectContaining({
  1093. event: "config.file.invalid",
  1094. level: "warn",
  1095. message: "Config file failed to load",
  1096. module: "adapters.config",
  1097. context: expect.objectContaining({
  1098. configPath: projectConfigPath,
  1099. configScope: "project",
  1100. diagnosticCode: "config_file_invalid",
  1101. }),
  1102. }),
  1103. ]);
  1104. } finally {
  1105. await rm(root, { force: true, recursive: true });
  1106. }
  1107. });
  1108. it("discovers project MCP config from the worktree root", async () => {
  1109. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1110. const cwd = join(root, "packages", "app");
  1111. try {
  1112. await mkdir(join(root, ".git"));
  1113. await mkdir(cwd, { recursive: true });
  1114. await writeFile(
  1115. join(root, "zcode.json"),
  1116. JSON.stringify({
  1117. mcp: {
  1118. servers: {
  1119. project: {
  1120. type: "stdio",
  1121. command: "node",
  1122. args: ["server.js"],
  1123. cwd: "tools",
  1124. },
  1125. },
  1126. },
  1127. }),
  1128. );
  1129. const result = createConfig({
  1130. env: {},
  1131. skipUserConfig: true,
  1132. workingDirectory: cwd,
  1133. });
  1134. expect(result.sources.project.loaded).toBe(true);
  1135. expect(result.sources.project.paths).toEqual([join(root, "zcode.json")]);
  1136. expect(result.sources.project.mcpServerNames).toEqual(["project"]);
  1137. expect(result.config.mcp.servers.project).toMatchObject({
  1138. type: "stdio",
  1139. command: "node",
  1140. cwd: join(root, "tools"),
  1141. });
  1142. } finally {
  1143. await rm(root, { force: true, recursive: true });
  1144. }
  1145. });
  1146. it("merges project configs from root to cwd with nearest config winning", async () => {
  1147. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1148. const cwd = join(root, "packages", "app");
  1149. const cwdConfigDir = join(cwd, ".zcode");
  1150. try {
  1151. await mkdir(join(root, ".git"));
  1152. await mkdir(cwdConfigDir, { recursive: true });
  1153. await writeFile(
  1154. join(root, "zcode.json"),
  1155. JSON.stringify({
  1156. mcp: {
  1157. servers: {
  1158. project: {
  1159. type: "stdio",
  1160. command: "root-server",
  1161. },
  1162. },
  1163. },
  1164. }),
  1165. );
  1166. await writeFile(
  1167. join(cwdConfigDir, "config.json"),
  1168. JSON.stringify({
  1169. mcp: {
  1170. servers: {
  1171. project: {
  1172. type: "stdio",
  1173. command: "nearest-server",
  1174. },
  1175. },
  1176. },
  1177. }),
  1178. );
  1179. const result = createConfig({
  1180. env: {},
  1181. skipUserConfig: true,
  1182. workingDirectory: cwd,
  1183. });
  1184. expect(result.sources.project.paths).toEqual([
  1185. join(root, "zcode.json"),
  1186. join(cwdConfigDir, "config.json"),
  1187. ]);
  1188. expect(result.config.mcp.servers.project).toMatchObject({
  1189. type: "stdio",
  1190. command: "nearest-server",
  1191. cwd,
  1192. });
  1193. } finally {
  1194. await rm(root, { force: true, recursive: true });
  1195. }
  1196. });
  1197. it("lets user MCP servers override same-name project MCP servers", async () => {
  1198. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1199. const userConfigPath = join(root, "home", "config.json");
  1200. try {
  1201. await mkdir(join(root, ".git"));
  1202. await mkdir(join(root, "home"), { recursive: true });
  1203. await writeFile(
  1204. join(root, "zcode.json"),
  1205. JSON.stringify({
  1206. mcp: {
  1207. servers: {
  1208. projectOnly: {
  1209. type: "stdio",
  1210. command: "project-only-server",
  1211. },
  1212. shared: {
  1213. type: "stdio",
  1214. command: "project-server",
  1215. },
  1216. },
  1217. },
  1218. }),
  1219. );
  1220. await writeFile(
  1221. userConfigPath,
  1222. JSON.stringify({
  1223. mcp: {
  1224. servers: {
  1225. shared: {
  1226. type: "stdio",
  1227. command: "user-server",
  1228. },
  1229. userOnly: {
  1230. type: "stdio",
  1231. command: "user-only-server",
  1232. },
  1233. },
  1234. },
  1235. }),
  1236. );
  1237. const result = createConfig({
  1238. env: {},
  1239. userConfigPath,
  1240. workingDirectory: root,
  1241. });
  1242. expect(result.config.mcp.servers.shared).toMatchObject({
  1243. type: "stdio",
  1244. command: "user-server",
  1245. });
  1246. expect(result.config.mcp.servers.projectOnly).toMatchObject({
  1247. command: "project-only-server",
  1248. });
  1249. expect(result.config.mcp.servers.userOnly).toMatchObject({
  1250. command: "user-only-server",
  1251. });
  1252. expect(result.sources.user.mcpServerNames).toEqual(["shared", "userOnly"]);
  1253. expect(result.sources.project.mcpServerNames.toSorted()).toEqual(["projectOnly", "shared"]);
  1254. expect(result.sources.mcp.serverSources).toMatchObject({
  1255. projectOnly: "project",
  1256. shared: "user",
  1257. userOnly: "user",
  1258. });
  1259. } finally {
  1260. await rm(root, { force: true, recursive: true });
  1261. }
  1262. });
  1263. it("does not scan project config above the worktree root", async () => {
  1264. const parent = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1265. const root = join(parent, "repo");
  1266. const cwd = join(root, "packages", "app");
  1267. try {
  1268. await mkdir(join(root, ".git"), { recursive: true });
  1269. await mkdir(cwd, { recursive: true });
  1270. await writeFile(
  1271. join(parent, "zcode.json"),
  1272. JSON.stringify({
  1273. mcp: {
  1274. servers: {
  1275. parent: {
  1276. type: "stdio",
  1277. command: "parent-server",
  1278. },
  1279. },
  1280. },
  1281. }),
  1282. );
  1283. const result = createConfig({
  1284. env: {},
  1285. skipUserConfig: true,
  1286. workingDirectory: cwd,
  1287. });
  1288. expect(result.sources.project.loaded).toBe(false);
  1289. expect(result.config.mcp.servers.parent).toBeUndefined();
  1290. } finally {
  1291. await rm(parent, { force: true, recursive: true });
  1292. }
  1293. });
  1294. it("keeps CLI feature overrides above project MCP config", async () => {
  1295. const root = await mkdtemp(join(tmpdir(), "zcode-project-config-"));
  1296. try {
  1297. await mkdir(join(root, ".git"));
  1298. await writeFile(
  1299. join(root, "zcode.json"),
  1300. JSON.stringify({
  1301. features: {
  1302. mcp: true,
  1303. },
  1304. }),
  1305. );
  1306. const result = createConfig({
  1307. cliOverrides: {
  1308. features: {
  1309. mcp: false,
  1310. },
  1311. },
  1312. env: {},
  1313. skipUserConfig: true,
  1314. workingDirectory: root,
  1315. });
  1316. expect(result.config.features.mcp).toBe(false);
  1317. } finally {
  1318. await rm(root, { force: true, recursive: true });
  1319. }
  1320. });
  1321. it("loads process hook config from file config", async () => {
  1322. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1323. const path = join(dir, "config.json");
  1324. try {
  1325. await writeFile(
  1326. path,
  1327. JSON.stringify({
  1328. hooks: {
  1329. enabled: true,
  1330. timeoutMs: 5000,
  1331. maxOutputBytes: 8192,
  1332. events: {
  1333. PreToolUse: [
  1334. {
  1335. matcher: "Bash",
  1336. hooks: [
  1337. {
  1338. type: "process",
  1339. command: "node",
  1340. args: ["hooks/pre-tool.js"],
  1341. enabled: false,
  1342. customFlag: "keep",
  1343. },
  1344. ],
  1345. },
  1346. ],
  1347. },
  1348. },
  1349. }),
  1350. );
  1351. const result = loadFileConfig(path);
  1352. expect(result.loaded).toBe(true);
  1353. expect(result.config.hooks).toMatchObject({
  1354. enabled: true,
  1355. timeoutMs: 5000,
  1356. maxOutputBytes: 8192,
  1357. });
  1358. expect(result.config.hooks?.events?.PreToolUse?.[0]?.hooks[0]).toMatchObject({
  1359. type: "process",
  1360. command: "node",
  1361. args: ["hooks/pre-tool.js"],
  1362. enabled: false,
  1363. customFlag: "keep",
  1364. });
  1365. } finally {
  1366. await rm(dir, { force: true, recursive: true });
  1367. }
  1368. });
  1369. it("drops hooks from discovered project config files because project hooks are untrusted code", async () => {
  1370. const root = await mkdtemp(join(tmpdir(), "zcode-project-hooks-"));
  1371. try {
  1372. await mkdir(join(root, ".git"));
  1373. await mkdir(join(root, ".zcode"), { recursive: true });
  1374. await writeFile(
  1375. join(root, "zcode.json"),
  1376. JSON.stringify({
  1377. hooks: {
  1378. enabled: true,
  1379. events: {
  1380. SessionStart: [
  1381. {
  1382. matcher: "startup",
  1383. hooks: [{ type: "command", command: "echo root-project-hook" }],
  1384. },
  1385. ],
  1386. },
  1387. },
  1388. }),
  1389. );
  1390. await writeFile(
  1391. join(root, ".zcode", "config.json"),
  1392. JSON.stringify({
  1393. hooks: {
  1394. enabled: true,
  1395. events: {
  1396. SessionStart: [
  1397. {
  1398. matcher: "startup",
  1399. hooks: [{ type: "command", command: "echo project-hook" }],
  1400. },
  1401. ],
  1402. },
  1403. },
  1404. }),
  1405. );
  1406. const result = createConfig({
  1407. env: {},
  1408. skipUserConfig: true,
  1409. workingDirectory: root,
  1410. });
  1411. expect(result.sources.project.loaded).toBe(true);
  1412. expect(
  1413. result.sources.project.diagnostics.filter(
  1414. (diagnostic) => diagnostic.code === "config_project_hooks_pending_trust",
  1415. ),
  1416. ).toHaveLength(2);
  1417. for (const configPath of [join(root, "zcode.json"), join(root, ".zcode", "config.json")]) {
  1418. expect(result.sources.project.diagnostics).toContainEqual(
  1419. expect.objectContaining({
  1420. code: "config_project_hooks_pending_trust",
  1421. filePath: configPath,
  1422. message: "Project hooks are pending workspace trust and remain blocked",
  1423. path: "hooks",
  1424. severity: "warning",
  1425. }),
  1426. );
  1427. }
  1428. expect(result.config.hooks.events.SessionStart).toBeUndefined();
  1429. expect(result.config.hooks.enabled).toBe(false);
  1430. } finally {
  1431. await rm(root, { force: true, recursive: true });
  1432. }
  1433. });
  1434. it("keeps user hooks while dropping untrusted project hooks", async () => {
  1435. const root = await mkdtemp(join(tmpdir(), "zcode-user-project-hooks-"));
  1436. const userConfigPath = join(root, "user-config.json");
  1437. try {
  1438. await mkdir(join(root, ".git"));
  1439. await mkdir(join(root, ".zcode"), { recursive: true });
  1440. await writeFile(
  1441. userConfigPath,
  1442. JSON.stringify({
  1443. hooks: {
  1444. enabled: true,
  1445. events: {
  1446. SessionStart: [
  1447. {
  1448. matcher: "startup",
  1449. hooks: [{ type: "command", command: "echo user-hook" }],
  1450. },
  1451. ],
  1452. },
  1453. },
  1454. }),
  1455. );
  1456. await writeFile(
  1457. join(root, ".zcode", "config.json"),
  1458. JSON.stringify({
  1459. hooks: {
  1460. enabled: true,
  1461. events: {
  1462. UserPromptSubmit: [
  1463. {
  1464. matcher: "*",
  1465. hooks: [{ type: "command", command: "echo project-hook" }],
  1466. },
  1467. ],
  1468. },
  1469. },
  1470. }),
  1471. );
  1472. const result = createConfig({
  1473. env: {},
  1474. userConfigPath,
  1475. workingDirectory: root,
  1476. });
  1477. expect(result.sources.user.loaded).toBe(true);
  1478. expect(result.sources.project.loaded).toBe(true);
  1479. expect(result.sources.project.diagnostics).toContainEqual(
  1480. expect.objectContaining({
  1481. code: "config_project_hooks_pending_trust",
  1482. path: "hooks",
  1483. severity: "warning",
  1484. }),
  1485. );
  1486. expect(result.config.hooks.enabled).toBe(true);
  1487. expect(result.config.hooks.events.SessionStart?.[0]?.hooks[0]).toMatchObject({
  1488. type: "command",
  1489. command: "echo user-hook",
  1490. source: { kind: "user", path: userConfigPath },
  1491. });
  1492. expect(result.config.hooks.events.UserPromptSubmit).toBeUndefined();
  1493. } finally {
  1494. await rm(root, { force: true, recursive: true });
  1495. }
  1496. });
  1497. it("loads model stream idle timeout config from file config", async () => {
  1498. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1499. const path = join(dir, "config.json");
  1500. try {
  1501. await writeFile(
  1502. path,
  1503. JSON.stringify({
  1504. modelStream: {
  1505. idleTimeoutMs: 120000,
  1506. },
  1507. }),
  1508. );
  1509. const result = loadFileConfig(path);
  1510. expect(result.loaded).toBe(true);
  1511. expect(result.config.modelStream).toMatchObject({
  1512. idleTimeoutMs: 120000,
  1513. });
  1514. } finally {
  1515. await rm(dir, { force: true, recursive: true });
  1516. }
  1517. });
  1518. it("merges model stream idle timeout into runtime config", async () => {
  1519. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1520. const path = join(dir, "config.json");
  1521. try {
  1522. await writeFile(
  1523. path,
  1524. JSON.stringify({
  1525. modelStream: {
  1526. idleTimeoutMs: 240000,
  1527. },
  1528. }),
  1529. );
  1530. const result = createConfig({ env: {}, userConfigPath: path });
  1531. expect(result.config.modelStream.idleTimeoutMs).toBe(240000);
  1532. } finally {
  1533. await rm(dir, { force: true, recursive: true });
  1534. }
  1535. });
  1536. it("loads model anomaly guard config from file config", async () => {
  1537. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1538. const path = join(dir, "config.json");
  1539. try {
  1540. await writeFile(
  1541. path,
  1542. JSON.stringify({
  1543. modelAnomalyGuard: {
  1544. repeatedToolCallWarningThreshold: 4,
  1545. maxBudgetWarningsPerTurn: 2,
  1546. },
  1547. }),
  1548. );
  1549. const result = loadFileConfig(path);
  1550. expect(result.loaded).toBe(true);
  1551. expect(result.config.modelAnomalyGuard).toMatchObject({
  1552. repeatedToolCallWarningThreshold: 4,
  1553. maxBudgetWarningsPerTurn: 2,
  1554. });
  1555. } finally {
  1556. await rm(dir, { force: true, recursive: true });
  1557. }
  1558. });
  1559. it("rejects unknown hook events from file config", async () => {
  1560. const dir = await mkdtemp(join(tmpdir(), "zcode-config-"));
  1561. const path = join(dir, "config.json");
  1562. try {
  1563. await writeFile(
  1564. path,
  1565. JSON.stringify({
  1566. hooks: {
  1567. enabled: true,
  1568. events: {
  1569. BeforeEverything: [
  1570. {
  1571. hooks: [
  1572. {
  1573. type: "process",
  1574. command: "node",
  1575. },
  1576. ],
  1577. },
  1578. ],
  1579. },
  1580. },
  1581. }),
  1582. );
  1583. const result = loadFileConfig(path);
  1584. expect(result.loaded).toBe(false);
  1585. expect(result.config).toEqual({});
  1586. } finally {
  1587. await rm(dir, { force: true, recursive: true });
  1588. }
  1589. });
  1590. // Provider/Model 配置已归 Registry 管理;通用配置忽略退场字段,不得重新推导模型选择。
  1591. it.each([
  1592. { model: { provider: "example", model: "example-model", apiKey: "fixture" } },
  1593. { model: { main: "example/main", lite: "example/lite" } },
  1594. { model: "example/main", modelSmall: "example/small", smallModel: "example/small" },
  1595. {
  1596. provider: {
  1597. example: {
  1598. kind: "unsupported",
  1599. npm: "fixture",
  1600. models: { tiny: { limit: { context: "invalid" } } },
  1601. },
  1602. },
  1603. },
  1604. { modelCatalog: { overrides: { "example/model": { supportsReasoning: true } } } },
  1605. ])(
  1606. "ignores retired provider config while preserving active configuration: %j",
  1607. async (legacy) => {
  1608. const dir = await mkdtemp(join(tmpdir(), "zcode-config-retired-model-"));
  1609. try {
  1610. const path = join(dir, "config.json");
  1611. await writeFile(path, JSON.stringify({ ...legacy, features: { memory: false } }));
  1612. const result = loadFileConfig(path);
  1613. expect(result.loaded).toBe(true);
  1614. expect(result.config).toMatchObject({ features: { memory: false } });
  1615. for (const key of ["model", "provider", "modelCatalog", "modelSmall", "smallModel"])
  1616. expect(result.config).not.toHaveProperty(key);
  1617. } finally {
  1618. await rm(dir, { recursive: true, force: true });
  1619. }
  1620. },
  1621. );
  1622. it("rejects invalid active configuration", async () => {
  1623. const dir = await mkdtemp(join(tmpdir(), "zcode-config-invalid-"));
  1624. try {
  1625. const path = join(dir, "config.json");
  1626. await writeFile(path, JSON.stringify({ network: { timeout: "invalid" } }));
  1627. const result = loadFileConfig(path);
  1628. expect(result.loaded).toBe(false);
  1629. expect(result.config).toEqual({});
  1630. } finally {
  1631. await rm(dir, { recursive: true, force: true });
  1632. }
  1633. });
  1634. it("removes a plugin's enabled flag and options on uninstall while preserving others", async () => {
  1635. const dir = await mkdtemp(join(tmpdir(), "zcode-config-plugin-remove-"));
  1636. const configPath = join(dir, "config.json");
  1637. try {
  1638. await writeFile(
  1639. configPath,
  1640. JSON.stringify({
  1641. plugins: {
  1642. enabledPlugins: {
  1643. "hello@market": true,
  1644. "keep@market": true,
  1645. },
  1646. options: {
  1647. "hello@market": { default_device: "iPhone 16" },
  1648. "keep@market": { foo: "bar" },
  1649. },
  1650. },
  1651. }),
  1652. );
  1653. const result = await removePluginFromFileConfig(configPath, "hello@market");
  1654. expect(result.removedEnabled).toBe(true);
  1655. expect(result.removedOptions).toBe(true);
  1656. const parsed = JSON.parse(await readFile(configPath, "utf8")) as {
  1657. plugins: {
  1658. enabledPlugins: Record<string, boolean>;
  1659. options: Record<string, unknown>;
  1660. };
  1661. };
  1662. expect(parsed.plugins.enabledPlugins).toEqual({ "keep@market": true });
  1663. expect(parsed.plugins.options).toEqual({ "keep@market": { foo: "bar" } });
  1664. } finally {
  1665. await rm(dir, { force: true, recursive: true });
  1666. }
  1667. });
  1668. it("is a no-op when removing a plugin that has no config footprint", async () => {
  1669. const dir = await mkdtemp(join(tmpdir(), "zcode-config-plugin-remove-missing-"));
  1670. const configPath = join(dir, "config.json");
  1671. try {
  1672. await writeFile(
  1673. configPath,
  1674. JSON.stringify({ plugins: { enabledPlugins: { "keep@market": true } } }),
  1675. );
  1676. const before = await readFile(configPath, "utf8");
  1677. const result = await removePluginFromFileConfig(configPath, "missing@market");
  1678. expect(result.removedEnabled).toBe(false);
  1679. expect(result.removedOptions).toBe(false);
  1680. // 未命中任何键时不应改写文件内容。
  1681. expect(await readFile(configPath, "utf8")).toBe(before);
  1682. } finally {
  1683. await rm(dir, { force: true, recursive: true });
  1684. }
  1685. });
  1686. it("adds and removes a suppressed builtin id atomically", async () => {
  1687. const dir = await mkdtemp(join(tmpdir(), "zcode-config-suppress-patch-"));
  1688. const path = join(dir, "config.json");
  1689. const id = "skill-creator@zcode-plugins-official";
  1690. const added = await addSuppressedBuiltinInFileConfig(path, id);
  1691. expect(added.suppressed).toBe(true);
  1692. expect(JSON.parse(await readFile(path, "utf8")).plugins.suppressedBuiltins).toEqual([id]);
  1693. // idempotent add
  1694. await addSuppressedBuiltinInFileConfig(path, id);
  1695. expect(JSON.parse(await readFile(path, "utf8")).plugins.suppressedBuiltins).toEqual([id]);
  1696. const removed = await removeSuppressedBuiltinInFileConfig(path, id);
  1697. expect(removed.suppressed).toBe(false);
  1698. expect(JSON.parse(await readFile(path, "utf8")).plugins.suppressedBuiltins).toEqual([]);
  1699. });
  1700. });
  1701. async function readLogEntries(logDir: string): Promise<Array<Record<string, unknown>>> {
  1702. const files = await readdir(logDir);
  1703. expect(files).toHaveLength(1);
  1704. const content = await readFile(join(logDir, files[0]!), "utf8");
  1705. return content.trim().split("\n").map(JSON.parse) as Array<Record<string, unknown>>;
  1706. }