config.test.ts 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886
  1. import { test, expect, describe, mock, afterEach } from "bun:test"
  2. import { Config } from "../../src/config/config"
  3. import { Instance } from "../../src/project/instance"
  4. import { Auth } from "../../src/auth"
  5. import { tmpdir } from "../fixture/fixture"
  6. import path from "path"
  7. import fs from "fs/promises"
  8. import { pathToFileURL } from "url"
  9. import { Global } from "../../src/global"
  10. import { Filesystem } from "../../src/util/filesystem"
  11. // Get managed config directory from environment (set in preload.ts)
  12. const managedConfigDir = process.env.OPENCODE_TEST_MANAGED_CONFIG_DIR!
  13. afterEach(async () => {
  14. await fs.rm(managedConfigDir, { force: true, recursive: true }).catch(() => {})
  15. })
  16. async function writeManagedSettings(settings: object, filename = "opencode.json") {
  17. await fs.mkdir(managedConfigDir, { recursive: true })
  18. await Filesystem.write(path.join(managedConfigDir, filename), JSON.stringify(settings))
  19. }
  20. async function writeConfig(dir: string, config: object, name = "opencode.json") {
  21. await Filesystem.write(path.join(dir, name), JSON.stringify(config))
  22. }
  23. test("loads config with defaults when no files exist", async () => {
  24. await using tmp = await tmpdir()
  25. await Instance.provide({
  26. directory: tmp.path,
  27. fn: async () => {
  28. const config = await Config.get()
  29. expect(config.username).toBeDefined()
  30. },
  31. })
  32. })
  33. test("loads JSON config file", async () => {
  34. await using tmp = await tmpdir({
  35. init: async (dir) => {
  36. await writeConfig(dir, {
  37. $schema: "https://opencode.ai/config.json",
  38. model: "test/model",
  39. username: "testuser",
  40. })
  41. },
  42. })
  43. await Instance.provide({
  44. directory: tmp.path,
  45. fn: async () => {
  46. const config = await Config.get()
  47. expect(config.model).toBe("test/model")
  48. expect(config.username).toBe("testuser")
  49. },
  50. })
  51. })
  52. test("ignores legacy tui keys in opencode config", async () => {
  53. await using tmp = await tmpdir({
  54. init: async (dir) => {
  55. await writeConfig(dir, {
  56. $schema: "https://opencode.ai/config.json",
  57. model: "test/model",
  58. theme: "legacy",
  59. tui: { scroll_speed: 4 },
  60. })
  61. },
  62. })
  63. await Instance.provide({
  64. directory: tmp.path,
  65. fn: async () => {
  66. const config = await Config.get()
  67. expect(config.model).toBe("test/model")
  68. expect((config as Record<string, unknown>).theme).toBeUndefined()
  69. expect((config as Record<string, unknown>).tui).toBeUndefined()
  70. },
  71. })
  72. })
  73. test("loads JSONC config file", async () => {
  74. await using tmp = await tmpdir({
  75. init: async (dir) => {
  76. await Filesystem.write(
  77. path.join(dir, "opencode.jsonc"),
  78. `{
  79. // This is a comment
  80. "$schema": "https://opencode.ai/config.json",
  81. "model": "test/model",
  82. "username": "testuser"
  83. }`,
  84. )
  85. },
  86. })
  87. await Instance.provide({
  88. directory: tmp.path,
  89. fn: async () => {
  90. const config = await Config.get()
  91. expect(config.model).toBe("test/model")
  92. expect(config.username).toBe("testuser")
  93. },
  94. })
  95. })
  96. test("merges multiple config files with correct precedence", async () => {
  97. await using tmp = await tmpdir({
  98. init: async (dir) => {
  99. await writeConfig(
  100. dir,
  101. {
  102. $schema: "https://opencode.ai/config.json",
  103. model: "base",
  104. username: "base",
  105. },
  106. "opencode.jsonc",
  107. )
  108. await writeConfig(dir, {
  109. $schema: "https://opencode.ai/config.json",
  110. model: "override",
  111. })
  112. },
  113. })
  114. await Instance.provide({
  115. directory: tmp.path,
  116. fn: async () => {
  117. const config = await Config.get()
  118. expect(config.model).toBe("override")
  119. expect(config.username).toBe("base")
  120. },
  121. })
  122. })
  123. test("handles environment variable substitution", async () => {
  124. const originalEnv = process.env["TEST_VAR"]
  125. process.env["TEST_VAR"] = "test-user"
  126. try {
  127. await using tmp = await tmpdir({
  128. init: async (dir) => {
  129. await writeConfig(dir, {
  130. $schema: "https://opencode.ai/config.json",
  131. username: "{env:TEST_VAR}",
  132. })
  133. },
  134. })
  135. await Instance.provide({
  136. directory: tmp.path,
  137. fn: async () => {
  138. const config = await Config.get()
  139. expect(config.username).toBe("test-user")
  140. },
  141. })
  142. } finally {
  143. if (originalEnv !== undefined) {
  144. process.env["TEST_VAR"] = originalEnv
  145. } else {
  146. delete process.env["TEST_VAR"]
  147. }
  148. }
  149. })
  150. test("preserves env variables when adding $schema to config", async () => {
  151. const originalEnv = process.env["PRESERVE_VAR"]
  152. process.env["PRESERVE_VAR"] = "secret_value"
  153. try {
  154. await using tmp = await tmpdir({
  155. init: async (dir) => {
  156. // Config without $schema - should trigger auto-add
  157. await Filesystem.write(
  158. path.join(dir, "opencode.json"),
  159. JSON.stringify({
  160. username: "{env:PRESERVE_VAR}",
  161. }),
  162. )
  163. },
  164. })
  165. await Instance.provide({
  166. directory: tmp.path,
  167. fn: async () => {
  168. const config = await Config.get()
  169. expect(config.username).toBe("secret_value")
  170. // Read the file to verify the env variable was preserved
  171. const content = await Filesystem.readText(path.join(tmp.path, "opencode.json"))
  172. expect(content).toContain("{env:PRESERVE_VAR}")
  173. expect(content).not.toContain("secret_value")
  174. expect(content).toContain("$schema")
  175. },
  176. })
  177. } finally {
  178. if (originalEnv !== undefined) {
  179. process.env["PRESERVE_VAR"] = originalEnv
  180. } else {
  181. delete process.env["PRESERVE_VAR"]
  182. }
  183. }
  184. })
  185. test("handles file inclusion substitution", async () => {
  186. await using tmp = await tmpdir({
  187. init: async (dir) => {
  188. await Filesystem.write(path.join(dir, "included.txt"), "test-user")
  189. await writeConfig(dir, {
  190. $schema: "https://opencode.ai/config.json",
  191. username: "{file:included.txt}",
  192. })
  193. },
  194. })
  195. await Instance.provide({
  196. directory: tmp.path,
  197. fn: async () => {
  198. const config = await Config.get()
  199. expect(config.username).toBe("test-user")
  200. },
  201. })
  202. })
  203. test("handles file inclusion with replacement tokens", async () => {
  204. await using tmp = await tmpdir({
  205. init: async (dir) => {
  206. await Filesystem.write(path.join(dir, "included.md"), "const out = await Bun.$`echo hi`")
  207. await writeConfig(dir, {
  208. $schema: "https://opencode.ai/config.json",
  209. username: "{file:included.md}",
  210. })
  211. },
  212. })
  213. await Instance.provide({
  214. directory: tmp.path,
  215. fn: async () => {
  216. const config = await Config.get()
  217. expect(config.username).toBe("const out = await Bun.$`echo hi`")
  218. },
  219. })
  220. })
  221. test("validates config schema and throws on invalid fields", async () => {
  222. await using tmp = await tmpdir({
  223. init: async (dir) => {
  224. await writeConfig(dir, {
  225. $schema: "https://opencode.ai/config.json",
  226. invalid_field: "should cause error",
  227. })
  228. },
  229. })
  230. await Instance.provide({
  231. directory: tmp.path,
  232. fn: async () => {
  233. // Strict schema should throw an error for invalid fields
  234. await expect(Config.get()).rejects.toThrow()
  235. },
  236. })
  237. })
  238. test("throws error for invalid JSON", async () => {
  239. await using tmp = await tmpdir({
  240. init: async (dir) => {
  241. await Filesystem.write(path.join(dir, "opencode.json"), "{ invalid json }")
  242. },
  243. })
  244. await Instance.provide({
  245. directory: tmp.path,
  246. fn: async () => {
  247. await expect(Config.get()).rejects.toThrow()
  248. },
  249. })
  250. })
  251. test("handles agent configuration", async () => {
  252. await using tmp = await tmpdir({
  253. init: async (dir) => {
  254. await writeConfig(dir, {
  255. $schema: "https://opencode.ai/config.json",
  256. agent: {
  257. test_agent: {
  258. model: "test/model",
  259. temperature: 0.7,
  260. description: "test agent",
  261. },
  262. },
  263. })
  264. },
  265. })
  266. await Instance.provide({
  267. directory: tmp.path,
  268. fn: async () => {
  269. const config = await Config.get()
  270. expect(config.agent?.["test_agent"]).toEqual(
  271. expect.objectContaining({
  272. model: "test/model",
  273. temperature: 0.7,
  274. description: "test agent",
  275. }),
  276. )
  277. },
  278. })
  279. })
  280. test("treats agent variant as model-scoped setting (not provider option)", async () => {
  281. await using tmp = await tmpdir({
  282. init: async (dir) => {
  283. await writeConfig(dir, {
  284. $schema: "https://opencode.ai/config.json",
  285. agent: {
  286. test_agent: {
  287. model: "openai/gpt-5.2",
  288. variant: "xhigh",
  289. max_tokens: 123,
  290. },
  291. },
  292. })
  293. },
  294. })
  295. await Instance.provide({
  296. directory: tmp.path,
  297. fn: async () => {
  298. const config = await Config.get()
  299. const agent = config.agent?.["test_agent"]
  300. expect(agent?.variant).toBe("xhigh")
  301. expect(agent?.options).toMatchObject({
  302. max_tokens: 123,
  303. })
  304. expect(agent?.options).not.toHaveProperty("variant")
  305. },
  306. })
  307. })
  308. test("handles command configuration", async () => {
  309. await using tmp = await tmpdir({
  310. init: async (dir) => {
  311. await writeConfig(dir, {
  312. $schema: "https://opencode.ai/config.json",
  313. command: {
  314. test_command: {
  315. template: "test template",
  316. description: "test command",
  317. agent: "test_agent",
  318. },
  319. },
  320. })
  321. },
  322. })
  323. await Instance.provide({
  324. directory: tmp.path,
  325. fn: async () => {
  326. const config = await Config.get()
  327. expect(config.command?.["test_command"]).toEqual({
  328. template: "test template",
  329. description: "test command",
  330. agent: "test_agent",
  331. })
  332. },
  333. })
  334. })
  335. test("migrates autoshare to share field", async () => {
  336. await using tmp = await tmpdir({
  337. init: async (dir) => {
  338. await Filesystem.write(
  339. path.join(dir, "opencode.json"),
  340. JSON.stringify({
  341. $schema: "https://opencode.ai/config.json",
  342. autoshare: true,
  343. }),
  344. )
  345. },
  346. })
  347. await Instance.provide({
  348. directory: tmp.path,
  349. fn: async () => {
  350. const config = await Config.get()
  351. expect(config.share).toBe("auto")
  352. expect(config.autoshare).toBe(true)
  353. },
  354. })
  355. })
  356. test("migrates mode field to agent field", async () => {
  357. await using tmp = await tmpdir({
  358. init: async (dir) => {
  359. await Filesystem.write(
  360. path.join(dir, "opencode.json"),
  361. JSON.stringify({
  362. $schema: "https://opencode.ai/config.json",
  363. mode: {
  364. test_mode: {
  365. model: "test/model",
  366. temperature: 0.5,
  367. },
  368. },
  369. }),
  370. )
  371. },
  372. })
  373. await Instance.provide({
  374. directory: tmp.path,
  375. fn: async () => {
  376. const config = await Config.get()
  377. expect(config.agent?.["test_mode"]).toEqual({
  378. model: "test/model",
  379. temperature: 0.5,
  380. mode: "primary",
  381. options: {},
  382. permission: {},
  383. })
  384. },
  385. })
  386. })
  387. test("loads config from .opencode directory", async () => {
  388. await using tmp = await tmpdir({
  389. init: async (dir) => {
  390. const opencodeDir = path.join(dir, ".opencode")
  391. await fs.mkdir(opencodeDir, { recursive: true })
  392. const agentDir = path.join(opencodeDir, "agent")
  393. await fs.mkdir(agentDir, { recursive: true })
  394. await Filesystem.write(
  395. path.join(agentDir, "test.md"),
  396. `---
  397. model: test/model
  398. ---
  399. Test agent prompt`,
  400. )
  401. },
  402. })
  403. await Instance.provide({
  404. directory: tmp.path,
  405. fn: async () => {
  406. const config = await Config.get()
  407. expect(config.agent?.["test"]).toEqual(
  408. expect.objectContaining({
  409. name: "test",
  410. model: "test/model",
  411. prompt: "Test agent prompt",
  412. }),
  413. )
  414. },
  415. })
  416. })
  417. test("loads agents from .opencode/agents (plural)", async () => {
  418. await using tmp = await tmpdir({
  419. init: async (dir) => {
  420. const opencodeDir = path.join(dir, ".opencode")
  421. await fs.mkdir(opencodeDir, { recursive: true })
  422. const agentsDir = path.join(opencodeDir, "agents")
  423. await fs.mkdir(path.join(agentsDir, "nested"), { recursive: true })
  424. await Filesystem.write(
  425. path.join(agentsDir, "helper.md"),
  426. `---
  427. model: test/model
  428. mode: subagent
  429. ---
  430. Helper agent prompt`,
  431. )
  432. await Filesystem.write(
  433. path.join(agentsDir, "nested", "child.md"),
  434. `---
  435. model: test/model
  436. mode: subagent
  437. ---
  438. Nested agent prompt`,
  439. )
  440. },
  441. })
  442. await Instance.provide({
  443. directory: tmp.path,
  444. fn: async () => {
  445. const config = await Config.get()
  446. expect(config.agent?.["helper"]).toMatchObject({
  447. name: "helper",
  448. model: "test/model",
  449. mode: "subagent",
  450. prompt: "Helper agent prompt",
  451. })
  452. expect(config.agent?.["nested/child"]).toMatchObject({
  453. name: "nested/child",
  454. model: "test/model",
  455. mode: "subagent",
  456. prompt: "Nested agent prompt",
  457. })
  458. },
  459. })
  460. })
  461. test("loads commands from .opencode/command (singular)", async () => {
  462. await using tmp = await tmpdir({
  463. init: async (dir) => {
  464. const opencodeDir = path.join(dir, ".opencode")
  465. await fs.mkdir(opencodeDir, { recursive: true })
  466. const commandDir = path.join(opencodeDir, "command")
  467. await fs.mkdir(path.join(commandDir, "nested"), { recursive: true })
  468. await Filesystem.write(
  469. path.join(commandDir, "hello.md"),
  470. `---
  471. description: Test command
  472. ---
  473. Hello from singular command`,
  474. )
  475. await Filesystem.write(
  476. path.join(commandDir, "nested", "child.md"),
  477. `---
  478. description: Nested command
  479. ---
  480. Nested command template`,
  481. )
  482. },
  483. })
  484. await Instance.provide({
  485. directory: tmp.path,
  486. fn: async () => {
  487. const config = await Config.get()
  488. expect(config.command?.["hello"]).toEqual({
  489. description: "Test command",
  490. template: "Hello from singular command",
  491. })
  492. expect(config.command?.["nested/child"]).toEqual({
  493. description: "Nested command",
  494. template: "Nested command template",
  495. })
  496. },
  497. })
  498. })
  499. test("loads commands from .opencode/commands (plural)", async () => {
  500. await using tmp = await tmpdir({
  501. init: async (dir) => {
  502. const opencodeDir = path.join(dir, ".opencode")
  503. await fs.mkdir(opencodeDir, { recursive: true })
  504. const commandsDir = path.join(opencodeDir, "commands")
  505. await fs.mkdir(path.join(commandsDir, "nested"), { recursive: true })
  506. await Filesystem.write(
  507. path.join(commandsDir, "hello.md"),
  508. `---
  509. description: Test command
  510. ---
  511. Hello from plural commands`,
  512. )
  513. await Filesystem.write(
  514. path.join(commandsDir, "nested", "child.md"),
  515. `---
  516. description: Nested command
  517. ---
  518. Nested command template`,
  519. )
  520. },
  521. })
  522. await Instance.provide({
  523. directory: tmp.path,
  524. fn: async () => {
  525. const config = await Config.get()
  526. expect(config.command?.["hello"]).toEqual({
  527. description: "Test command",
  528. template: "Hello from plural commands",
  529. })
  530. expect(config.command?.["nested/child"]).toEqual({
  531. description: "Nested command",
  532. template: "Nested command template",
  533. })
  534. },
  535. })
  536. })
  537. test("updates config and writes to file", async () => {
  538. await using tmp = await tmpdir()
  539. await Instance.provide({
  540. directory: tmp.path,
  541. fn: async () => {
  542. const newConfig = { model: "updated/model" }
  543. await Config.update(newConfig as any)
  544. const writtenConfig = await Filesystem.readJson(path.join(tmp.path, "config.json"))
  545. expect(writtenConfig.model).toBe("updated/model")
  546. },
  547. })
  548. })
  549. test("gets config directories", async () => {
  550. await using tmp = await tmpdir()
  551. await Instance.provide({
  552. directory: tmp.path,
  553. fn: async () => {
  554. const dirs = await Config.directories()
  555. expect(dirs.length).toBeGreaterThanOrEqual(1)
  556. },
  557. })
  558. })
  559. test("does not try to install dependencies in read-only OPENCODE_CONFIG_DIR", async () => {
  560. if (process.platform === "win32") return
  561. await using tmp = await tmpdir<string>({
  562. init: async (dir) => {
  563. const ro = path.join(dir, "readonly")
  564. await fs.mkdir(ro, { recursive: true })
  565. await fs.chmod(ro, 0o555)
  566. return ro
  567. },
  568. dispose: async (dir) => {
  569. const ro = path.join(dir, "readonly")
  570. await fs.chmod(ro, 0o755).catch(() => {})
  571. return ro
  572. },
  573. })
  574. const prev = process.env.OPENCODE_CONFIG_DIR
  575. process.env.OPENCODE_CONFIG_DIR = tmp.extra
  576. try {
  577. await Instance.provide({
  578. directory: tmp.path,
  579. fn: async () => {
  580. await Config.get()
  581. },
  582. })
  583. } finally {
  584. if (prev === undefined) delete process.env.OPENCODE_CONFIG_DIR
  585. else process.env.OPENCODE_CONFIG_DIR = prev
  586. }
  587. })
  588. test("installs dependencies in writable OPENCODE_CONFIG_DIR", async () => {
  589. await using tmp = await tmpdir<string>({
  590. init: async (dir) => {
  591. const cfg = path.join(dir, "configdir")
  592. await fs.mkdir(cfg, { recursive: true })
  593. return cfg
  594. },
  595. })
  596. const prev = process.env.OPENCODE_CONFIG_DIR
  597. process.env.OPENCODE_CONFIG_DIR = tmp.extra
  598. try {
  599. await Instance.provide({
  600. directory: tmp.path,
  601. fn: async () => {
  602. await Config.get()
  603. await Config.waitForDependencies()
  604. },
  605. })
  606. expect(await Filesystem.exists(path.join(tmp.extra, "package.json"))).toBe(true)
  607. expect(await Filesystem.exists(path.join(tmp.extra, ".gitignore"))).toBe(true)
  608. } finally {
  609. if (prev === undefined) delete process.env.OPENCODE_CONFIG_DIR
  610. else process.env.OPENCODE_CONFIG_DIR = prev
  611. }
  612. })
  613. test("resolves scoped npm plugins in config", async () => {
  614. await using tmp = await tmpdir({
  615. init: async (dir) => {
  616. const pluginDir = path.join(dir, "node_modules", "@scope", "plugin")
  617. await fs.mkdir(pluginDir, { recursive: true })
  618. await Filesystem.write(
  619. path.join(dir, "package.json"),
  620. JSON.stringify({ name: "config-fixture", version: "1.0.0", type: "module" }, null, 2),
  621. )
  622. await Filesystem.write(
  623. path.join(pluginDir, "package.json"),
  624. JSON.stringify(
  625. {
  626. name: "@scope/plugin",
  627. version: "1.0.0",
  628. type: "module",
  629. main: "./index.js",
  630. },
  631. null,
  632. 2,
  633. ),
  634. )
  635. await Filesystem.write(path.join(pluginDir, "index.js"), "export default {}\n")
  636. await Filesystem.write(
  637. path.join(dir, "opencode.json"),
  638. JSON.stringify({ $schema: "https://opencode.ai/config.json", plugin: ["@scope/plugin"] }, null, 2),
  639. )
  640. },
  641. })
  642. await Instance.provide({
  643. directory: tmp.path,
  644. fn: async () => {
  645. const config = await Config.get()
  646. const pluginEntries = config.plugin ?? []
  647. const baseUrl = pathToFileURL(path.join(tmp.path, "opencode.json")).href
  648. const expected = pathToFileURL(path.join(tmp.path, "node_modules", "@scope", "plugin", "index.js")).href
  649. expect(pluginEntries.includes(expected)).toBe(true)
  650. const scopedEntry = pluginEntries.find((entry) => entry === expected)
  651. expect(scopedEntry).toBeDefined()
  652. expect(scopedEntry?.includes("/node_modules/@scope/plugin/")).toBe(true)
  653. },
  654. })
  655. })
  656. test("merges plugin arrays from global and local configs", async () => {
  657. await using tmp = await tmpdir({
  658. init: async (dir) => {
  659. // Create a nested project structure with local .opencode config
  660. const projectDir = path.join(dir, "project")
  661. const opencodeDir = path.join(projectDir, ".opencode")
  662. await fs.mkdir(opencodeDir, { recursive: true })
  663. // Global config with plugins
  664. await Filesystem.write(
  665. path.join(dir, "opencode.json"),
  666. JSON.stringify({
  667. $schema: "https://opencode.ai/config.json",
  668. plugin: ["global-plugin-1", "global-plugin-2"],
  669. }),
  670. )
  671. // Local .opencode config with different plugins
  672. await Filesystem.write(
  673. path.join(opencodeDir, "opencode.json"),
  674. JSON.stringify({
  675. $schema: "https://opencode.ai/config.json",
  676. plugin: ["local-plugin-1"],
  677. }),
  678. )
  679. },
  680. })
  681. await Instance.provide({
  682. directory: path.join(tmp.path, "project"),
  683. fn: async () => {
  684. const config = await Config.get()
  685. const plugins = config.plugin ?? []
  686. // Should contain both global and local plugins
  687. expect(plugins.some((p) => p.includes("global-plugin-1"))).toBe(true)
  688. expect(plugins.some((p) => p.includes("global-plugin-2"))).toBe(true)
  689. expect(plugins.some((p) => p.includes("local-plugin-1"))).toBe(true)
  690. // Should have all 3 plugins (not replaced, but merged)
  691. const pluginNames = plugins.filter((p) => p.includes("global-plugin") || p.includes("local-plugin"))
  692. expect(pluginNames.length).toBeGreaterThanOrEqual(3)
  693. },
  694. })
  695. })
  696. test("does not error when only custom agent is a subagent", async () => {
  697. await using tmp = await tmpdir({
  698. init: async (dir) => {
  699. const opencodeDir = path.join(dir, ".opencode")
  700. await fs.mkdir(opencodeDir, { recursive: true })
  701. const agentDir = path.join(opencodeDir, "agent")
  702. await fs.mkdir(agentDir, { recursive: true })
  703. await Filesystem.write(
  704. path.join(agentDir, "helper.md"),
  705. `---
  706. model: test/model
  707. mode: subagent
  708. ---
  709. Helper subagent prompt`,
  710. )
  711. },
  712. })
  713. await Instance.provide({
  714. directory: tmp.path,
  715. fn: async () => {
  716. const config = await Config.get()
  717. expect(config.agent?.["helper"]).toMatchObject({
  718. name: "helper",
  719. model: "test/model",
  720. mode: "subagent",
  721. prompt: "Helper subagent prompt",
  722. })
  723. },
  724. })
  725. })
  726. test("merges instructions arrays from global and local configs", async () => {
  727. await using tmp = await tmpdir({
  728. init: async (dir) => {
  729. const projectDir = path.join(dir, "project")
  730. const opencodeDir = path.join(projectDir, ".opencode")
  731. await fs.mkdir(opencodeDir, { recursive: true })
  732. await Filesystem.write(
  733. path.join(dir, "opencode.json"),
  734. JSON.stringify({
  735. $schema: "https://opencode.ai/config.json",
  736. instructions: ["global-instructions.md", "shared-rules.md"],
  737. }),
  738. )
  739. await Filesystem.write(
  740. path.join(opencodeDir, "opencode.json"),
  741. JSON.stringify({
  742. $schema: "https://opencode.ai/config.json",
  743. instructions: ["local-instructions.md"],
  744. }),
  745. )
  746. },
  747. })
  748. await Instance.provide({
  749. directory: path.join(tmp.path, "project"),
  750. fn: async () => {
  751. const config = await Config.get()
  752. const instructions = config.instructions ?? []
  753. expect(instructions).toContain("global-instructions.md")
  754. expect(instructions).toContain("shared-rules.md")
  755. expect(instructions).toContain("local-instructions.md")
  756. expect(instructions.length).toBe(3)
  757. },
  758. })
  759. })
  760. test("deduplicates duplicate instructions from global and local configs", async () => {
  761. await using tmp = await tmpdir({
  762. init: async (dir) => {
  763. const projectDir = path.join(dir, "project")
  764. const opencodeDir = path.join(projectDir, ".opencode")
  765. await fs.mkdir(opencodeDir, { recursive: true })
  766. await Filesystem.write(
  767. path.join(dir, "opencode.json"),
  768. JSON.stringify({
  769. $schema: "https://opencode.ai/config.json",
  770. instructions: ["duplicate.md", "global-only.md"],
  771. }),
  772. )
  773. await Filesystem.write(
  774. path.join(opencodeDir, "opencode.json"),
  775. JSON.stringify({
  776. $schema: "https://opencode.ai/config.json",
  777. instructions: ["duplicate.md", "local-only.md"],
  778. }),
  779. )
  780. },
  781. })
  782. await Instance.provide({
  783. directory: path.join(tmp.path, "project"),
  784. fn: async () => {
  785. const config = await Config.get()
  786. const instructions = config.instructions ?? []
  787. expect(instructions).toContain("global-only.md")
  788. expect(instructions).toContain("local-only.md")
  789. expect(instructions).toContain("duplicate.md")
  790. const duplicates = instructions.filter((i) => i === "duplicate.md")
  791. expect(duplicates.length).toBe(1)
  792. expect(instructions.length).toBe(3)
  793. },
  794. })
  795. })
  796. test("deduplicates duplicate plugins from global and local configs", async () => {
  797. await using tmp = await tmpdir({
  798. init: async (dir) => {
  799. // Create a nested project structure with local .opencode config
  800. const projectDir = path.join(dir, "project")
  801. const opencodeDir = path.join(projectDir, ".opencode")
  802. await fs.mkdir(opencodeDir, { recursive: true })
  803. // Global config with plugins
  804. await Filesystem.write(
  805. path.join(dir, "opencode.json"),
  806. JSON.stringify({
  807. $schema: "https://opencode.ai/config.json",
  808. plugin: ["duplicate-plugin", "global-plugin-1"],
  809. }),
  810. )
  811. // Local .opencode config with some overlapping plugins
  812. await Filesystem.write(
  813. path.join(opencodeDir, "opencode.json"),
  814. JSON.stringify({
  815. $schema: "https://opencode.ai/config.json",
  816. plugin: ["duplicate-plugin", "local-plugin-1"],
  817. }),
  818. )
  819. },
  820. })
  821. await Instance.provide({
  822. directory: path.join(tmp.path, "project"),
  823. fn: async () => {
  824. const config = await Config.get()
  825. const plugins = config.plugin ?? []
  826. // Should contain all unique plugins
  827. expect(plugins.some((p) => p.includes("global-plugin-1"))).toBe(true)
  828. expect(plugins.some((p) => p.includes("local-plugin-1"))).toBe(true)
  829. expect(plugins.some((p) => p.includes("duplicate-plugin"))).toBe(true)
  830. // Should deduplicate the duplicate plugin
  831. const duplicatePlugins = plugins.filter((p) => p.includes("duplicate-plugin"))
  832. expect(duplicatePlugins.length).toBe(1)
  833. // Should have exactly 3 unique plugins
  834. const pluginNames = plugins.filter(
  835. (p) => p.includes("global-plugin") || p.includes("local-plugin") || p.includes("duplicate-plugin"),
  836. )
  837. expect(pluginNames.length).toBe(3)
  838. },
  839. })
  840. })
  841. // Legacy tools migration tests
  842. test("migrates legacy tools config to permissions - allow", async () => {
  843. await using tmp = await tmpdir({
  844. init: async (dir) => {
  845. await Filesystem.write(
  846. path.join(dir, "opencode.json"),
  847. JSON.stringify({
  848. $schema: "https://opencode.ai/config.json",
  849. agent: {
  850. test: {
  851. tools: {
  852. bash: true,
  853. read: true,
  854. },
  855. },
  856. },
  857. }),
  858. )
  859. },
  860. })
  861. await Instance.provide({
  862. directory: tmp.path,
  863. fn: async () => {
  864. const config = await Config.get()
  865. expect(config.agent?.["test"]?.permission).toEqual({
  866. bash: "allow",
  867. read: "allow",
  868. })
  869. },
  870. })
  871. })
  872. test("migrates legacy tools config to permissions - deny", async () => {
  873. await using tmp = await tmpdir({
  874. init: async (dir) => {
  875. await Filesystem.write(
  876. path.join(dir, "opencode.json"),
  877. JSON.stringify({
  878. $schema: "https://opencode.ai/config.json",
  879. agent: {
  880. test: {
  881. tools: {
  882. bash: false,
  883. webfetch: false,
  884. },
  885. },
  886. },
  887. }),
  888. )
  889. },
  890. })
  891. await Instance.provide({
  892. directory: tmp.path,
  893. fn: async () => {
  894. const config = await Config.get()
  895. expect(config.agent?.["test"]?.permission).toEqual({
  896. bash: "deny",
  897. webfetch: "deny",
  898. })
  899. },
  900. })
  901. })
  902. test("migrates legacy write tool to edit permission", async () => {
  903. await using tmp = await tmpdir({
  904. init: async (dir) => {
  905. await Filesystem.write(
  906. path.join(dir, "opencode.json"),
  907. JSON.stringify({
  908. $schema: "https://opencode.ai/config.json",
  909. agent: {
  910. test: {
  911. tools: {
  912. write: true,
  913. },
  914. },
  915. },
  916. }),
  917. )
  918. },
  919. })
  920. await Instance.provide({
  921. directory: tmp.path,
  922. fn: async () => {
  923. const config = await Config.get()
  924. expect(config.agent?.["test"]?.permission).toEqual({
  925. edit: "allow",
  926. })
  927. },
  928. })
  929. })
  930. // Managed settings tests
  931. // Note: preload.ts sets OPENCODE_TEST_MANAGED_CONFIG which Global.Path.managedConfig uses
  932. test("managed settings override user settings", async () => {
  933. await using tmp = await tmpdir({
  934. init: async (dir) => {
  935. await writeConfig(dir, {
  936. $schema: "https://opencode.ai/config.json",
  937. model: "user/model",
  938. share: "auto",
  939. username: "testuser",
  940. })
  941. },
  942. })
  943. await writeManagedSettings({
  944. $schema: "https://opencode.ai/config.json",
  945. model: "managed/model",
  946. share: "disabled",
  947. })
  948. await Instance.provide({
  949. directory: tmp.path,
  950. fn: async () => {
  951. const config = await Config.get()
  952. expect(config.model).toBe("managed/model")
  953. expect(config.share).toBe("disabled")
  954. expect(config.username).toBe("testuser")
  955. },
  956. })
  957. })
  958. test("managed settings override project settings", async () => {
  959. await using tmp = await tmpdir({
  960. init: async (dir) => {
  961. await writeConfig(dir, {
  962. $schema: "https://opencode.ai/config.json",
  963. autoupdate: true,
  964. disabled_providers: [],
  965. })
  966. },
  967. })
  968. await writeManagedSettings({
  969. $schema: "https://opencode.ai/config.json",
  970. autoupdate: false,
  971. disabled_providers: ["openai"],
  972. })
  973. await Instance.provide({
  974. directory: tmp.path,
  975. fn: async () => {
  976. const config = await Config.get()
  977. expect(config.autoupdate).toBe(false)
  978. expect(config.disabled_providers).toEqual(["openai"])
  979. },
  980. })
  981. })
  982. test("missing managed settings file is not an error", async () => {
  983. await using tmp = await tmpdir({
  984. init: async (dir) => {
  985. await writeConfig(dir, {
  986. $schema: "https://opencode.ai/config.json",
  987. model: "user/model",
  988. })
  989. },
  990. })
  991. await Instance.provide({
  992. directory: tmp.path,
  993. fn: async () => {
  994. const config = await Config.get()
  995. expect(config.model).toBe("user/model")
  996. },
  997. })
  998. })
  999. test("migrates legacy edit tool to edit permission", async () => {
  1000. await using tmp = await tmpdir({
  1001. init: async (dir) => {
  1002. await Filesystem.write(
  1003. path.join(dir, "opencode.json"),
  1004. JSON.stringify({
  1005. $schema: "https://opencode.ai/config.json",
  1006. agent: {
  1007. test: {
  1008. tools: {
  1009. edit: false,
  1010. },
  1011. },
  1012. },
  1013. }),
  1014. )
  1015. },
  1016. })
  1017. await Instance.provide({
  1018. directory: tmp.path,
  1019. fn: async () => {
  1020. const config = await Config.get()
  1021. expect(config.agent?.["test"]?.permission).toEqual({
  1022. edit: "deny",
  1023. })
  1024. },
  1025. })
  1026. })
  1027. test("migrates legacy patch tool to edit permission", async () => {
  1028. await using tmp = await tmpdir({
  1029. init: async (dir) => {
  1030. await Filesystem.write(
  1031. path.join(dir, "opencode.json"),
  1032. JSON.stringify({
  1033. $schema: "https://opencode.ai/config.json",
  1034. agent: {
  1035. test: {
  1036. tools: {
  1037. patch: true,
  1038. },
  1039. },
  1040. },
  1041. }),
  1042. )
  1043. },
  1044. })
  1045. await Instance.provide({
  1046. directory: tmp.path,
  1047. fn: async () => {
  1048. const config = await Config.get()
  1049. expect(config.agent?.["test"]?.permission).toEqual({
  1050. edit: "allow",
  1051. })
  1052. },
  1053. })
  1054. })
  1055. test("migrates legacy multiedit tool to edit permission", async () => {
  1056. await using tmp = await tmpdir({
  1057. init: async (dir) => {
  1058. await Filesystem.write(
  1059. path.join(dir, "opencode.json"),
  1060. JSON.stringify({
  1061. $schema: "https://opencode.ai/config.json",
  1062. agent: {
  1063. test: {
  1064. tools: {
  1065. multiedit: false,
  1066. },
  1067. },
  1068. },
  1069. }),
  1070. )
  1071. },
  1072. })
  1073. await Instance.provide({
  1074. directory: tmp.path,
  1075. fn: async () => {
  1076. const config = await Config.get()
  1077. expect(config.agent?.["test"]?.permission).toEqual({
  1078. edit: "deny",
  1079. })
  1080. },
  1081. })
  1082. })
  1083. test("migrates mixed legacy tools config", async () => {
  1084. await using tmp = await tmpdir({
  1085. init: async (dir) => {
  1086. await Filesystem.write(
  1087. path.join(dir, "opencode.json"),
  1088. JSON.stringify({
  1089. $schema: "https://opencode.ai/config.json",
  1090. agent: {
  1091. test: {
  1092. tools: {
  1093. bash: true,
  1094. write: true,
  1095. read: false,
  1096. webfetch: true,
  1097. },
  1098. },
  1099. },
  1100. }),
  1101. )
  1102. },
  1103. })
  1104. await Instance.provide({
  1105. directory: tmp.path,
  1106. fn: async () => {
  1107. const config = await Config.get()
  1108. expect(config.agent?.["test"]?.permission).toEqual({
  1109. bash: "allow",
  1110. edit: "allow",
  1111. read: "deny",
  1112. webfetch: "allow",
  1113. })
  1114. },
  1115. })
  1116. })
  1117. test("merges legacy tools with existing permission config", async () => {
  1118. await using tmp = await tmpdir({
  1119. init: async (dir) => {
  1120. await Filesystem.write(
  1121. path.join(dir, "opencode.json"),
  1122. JSON.stringify({
  1123. $schema: "https://opencode.ai/config.json",
  1124. agent: {
  1125. test: {
  1126. permission: {
  1127. glob: "allow",
  1128. },
  1129. tools: {
  1130. bash: true,
  1131. },
  1132. },
  1133. },
  1134. }),
  1135. )
  1136. },
  1137. })
  1138. await Instance.provide({
  1139. directory: tmp.path,
  1140. fn: async () => {
  1141. const config = await Config.get()
  1142. expect(config.agent?.["test"]?.permission).toEqual({
  1143. glob: "allow",
  1144. bash: "allow",
  1145. })
  1146. },
  1147. })
  1148. })
  1149. test("permission config preserves key order", async () => {
  1150. await using tmp = await tmpdir({
  1151. init: async (dir) => {
  1152. await Filesystem.write(
  1153. path.join(dir, "opencode.json"),
  1154. JSON.stringify({
  1155. $schema: "https://opencode.ai/config.json",
  1156. permission: {
  1157. "*": "deny",
  1158. edit: "ask",
  1159. write: "ask",
  1160. external_directory: "ask",
  1161. read: "allow",
  1162. todowrite: "allow",
  1163. todoread: "allow",
  1164. "thoughts_*": "allow",
  1165. "reasoning_model_*": "allow",
  1166. "tools_*": "allow",
  1167. "pr_comments_*": "allow",
  1168. },
  1169. }),
  1170. )
  1171. },
  1172. })
  1173. await Instance.provide({
  1174. directory: tmp.path,
  1175. fn: async () => {
  1176. const config = await Config.get()
  1177. expect(Object.keys(config.permission!)).toEqual([
  1178. "*",
  1179. "edit",
  1180. "write",
  1181. "external_directory",
  1182. "read",
  1183. "todowrite",
  1184. "todoread",
  1185. "thoughts_*",
  1186. "reasoning_model_*",
  1187. "tools_*",
  1188. "pr_comments_*",
  1189. ])
  1190. },
  1191. })
  1192. })
  1193. // MCP config merging tests
  1194. test("project config can override MCP server enabled status", async () => {
  1195. await using tmp = await tmpdir({
  1196. init: async (dir) => {
  1197. // Simulates a base config (like from remote .well-known) with disabled MCP
  1198. await Filesystem.write(
  1199. path.join(dir, "opencode.jsonc"),
  1200. JSON.stringify({
  1201. $schema: "https://opencode.ai/config.json",
  1202. mcp: {
  1203. jira: {
  1204. type: "remote",
  1205. url: "https://jira.example.com/mcp",
  1206. enabled: false,
  1207. },
  1208. wiki: {
  1209. type: "remote",
  1210. url: "https://wiki.example.com/mcp",
  1211. enabled: false,
  1212. },
  1213. },
  1214. }),
  1215. )
  1216. // Project config enables just jira
  1217. await Filesystem.write(
  1218. path.join(dir, "opencode.json"),
  1219. JSON.stringify({
  1220. $schema: "https://opencode.ai/config.json",
  1221. mcp: {
  1222. jira: {
  1223. type: "remote",
  1224. url: "https://jira.example.com/mcp",
  1225. enabled: true,
  1226. },
  1227. },
  1228. }),
  1229. )
  1230. },
  1231. })
  1232. await Instance.provide({
  1233. directory: tmp.path,
  1234. fn: async () => {
  1235. const config = await Config.get()
  1236. // jira should be enabled (overridden by project config)
  1237. expect(config.mcp?.jira).toEqual({
  1238. type: "remote",
  1239. url: "https://jira.example.com/mcp",
  1240. enabled: true,
  1241. })
  1242. // wiki should still be disabled (not overridden)
  1243. expect(config.mcp?.wiki).toEqual({
  1244. type: "remote",
  1245. url: "https://wiki.example.com/mcp",
  1246. enabled: false,
  1247. })
  1248. },
  1249. })
  1250. })
  1251. test("MCP config deep merges preserving base config properties", async () => {
  1252. await using tmp = await tmpdir({
  1253. init: async (dir) => {
  1254. // Base config with full MCP definition
  1255. await Filesystem.write(
  1256. path.join(dir, "opencode.jsonc"),
  1257. JSON.stringify({
  1258. $schema: "https://opencode.ai/config.json",
  1259. mcp: {
  1260. myserver: {
  1261. type: "remote",
  1262. url: "https://myserver.example.com/mcp",
  1263. enabled: false,
  1264. headers: {
  1265. "X-Custom-Header": "value",
  1266. },
  1267. },
  1268. },
  1269. }),
  1270. )
  1271. // Override just enables it, should preserve other properties
  1272. await Filesystem.write(
  1273. path.join(dir, "opencode.json"),
  1274. JSON.stringify({
  1275. $schema: "https://opencode.ai/config.json",
  1276. mcp: {
  1277. myserver: {
  1278. type: "remote",
  1279. url: "https://myserver.example.com/mcp",
  1280. enabled: true,
  1281. },
  1282. },
  1283. }),
  1284. )
  1285. },
  1286. })
  1287. await Instance.provide({
  1288. directory: tmp.path,
  1289. fn: async () => {
  1290. const config = await Config.get()
  1291. expect(config.mcp?.myserver).toEqual({
  1292. type: "remote",
  1293. url: "https://myserver.example.com/mcp",
  1294. enabled: true,
  1295. headers: {
  1296. "X-Custom-Header": "value",
  1297. },
  1298. })
  1299. },
  1300. })
  1301. })
  1302. test("local .opencode config can override MCP from project config", async () => {
  1303. await using tmp = await tmpdir({
  1304. init: async (dir) => {
  1305. // Project config with disabled MCP
  1306. await Filesystem.write(
  1307. path.join(dir, "opencode.json"),
  1308. JSON.stringify({
  1309. $schema: "https://opencode.ai/config.json",
  1310. mcp: {
  1311. docs: {
  1312. type: "remote",
  1313. url: "https://docs.example.com/mcp",
  1314. enabled: false,
  1315. },
  1316. },
  1317. }),
  1318. )
  1319. // Local .opencode directory config enables it
  1320. const opencodeDir = path.join(dir, ".opencode")
  1321. await fs.mkdir(opencodeDir, { recursive: true })
  1322. await Filesystem.write(
  1323. path.join(opencodeDir, "opencode.json"),
  1324. JSON.stringify({
  1325. $schema: "https://opencode.ai/config.json",
  1326. mcp: {
  1327. docs: {
  1328. type: "remote",
  1329. url: "https://docs.example.com/mcp",
  1330. enabled: true,
  1331. },
  1332. },
  1333. }),
  1334. )
  1335. },
  1336. })
  1337. await Instance.provide({
  1338. directory: tmp.path,
  1339. fn: async () => {
  1340. const config = await Config.get()
  1341. expect(config.mcp?.docs?.enabled).toBe(true)
  1342. },
  1343. })
  1344. })
  1345. test("project config overrides remote well-known config", async () => {
  1346. const originalFetch = globalThis.fetch
  1347. let fetchedUrl: string | undefined
  1348. const mockFetch = mock((url: string | URL | Request) => {
  1349. const urlStr = url.toString()
  1350. if (urlStr.includes(".well-known/opencode")) {
  1351. fetchedUrl = urlStr
  1352. return Promise.resolve(
  1353. new Response(
  1354. JSON.stringify({
  1355. config: {
  1356. mcp: {
  1357. jira: {
  1358. type: "remote",
  1359. url: "https://jira.example.com/mcp",
  1360. enabled: false,
  1361. },
  1362. },
  1363. },
  1364. }),
  1365. { status: 200 },
  1366. ),
  1367. )
  1368. }
  1369. return originalFetch(url)
  1370. })
  1371. globalThis.fetch = mockFetch as unknown as typeof fetch
  1372. const originalAuthAll = Auth.all
  1373. Auth.all = mock(() =>
  1374. Promise.resolve({
  1375. "https://example.com": {
  1376. type: "wellknown" as const,
  1377. key: "TEST_TOKEN",
  1378. token: "test-token",
  1379. },
  1380. }),
  1381. )
  1382. try {
  1383. await using tmp = await tmpdir({
  1384. git: true,
  1385. init: async (dir) => {
  1386. // Project config enables jira (overriding remote default)
  1387. await Filesystem.write(
  1388. path.join(dir, "opencode.json"),
  1389. JSON.stringify({
  1390. $schema: "https://opencode.ai/config.json",
  1391. mcp: {
  1392. jira: {
  1393. type: "remote",
  1394. url: "https://jira.example.com/mcp",
  1395. enabled: true,
  1396. },
  1397. },
  1398. }),
  1399. )
  1400. },
  1401. })
  1402. await Instance.provide({
  1403. directory: tmp.path,
  1404. fn: async () => {
  1405. const config = await Config.get()
  1406. // Verify fetch was called for wellknown config
  1407. expect(fetchedUrl).toBe("https://example.com/.well-known/opencode")
  1408. // Project config (enabled: true) should override remote (enabled: false)
  1409. expect(config.mcp?.jira?.enabled).toBe(true)
  1410. },
  1411. })
  1412. } finally {
  1413. globalThis.fetch = originalFetch
  1414. Auth.all = originalAuthAll
  1415. }
  1416. })
  1417. describe("getPluginName", () => {
  1418. test("extracts name from file:// URL", () => {
  1419. expect(Config.getPluginName("file:///path/to/plugin/foo.js")).toBe("foo")
  1420. expect(Config.getPluginName("file:///path/to/plugin/bar.ts")).toBe("bar")
  1421. expect(Config.getPluginName("file:///some/path/my-plugin.js")).toBe("my-plugin")
  1422. })
  1423. test("extracts name from npm package with version", () => {
  1424. expect(Config.getPluginName("[email protected]")).toBe("oh-my-opencode")
  1425. expect(Config.getPluginName("[email protected]")).toBe("some-plugin")
  1426. expect(Config.getPluginName("plugin@latest")).toBe("plugin")
  1427. })
  1428. test("extracts name from scoped npm package", () => {
  1429. expect(Config.getPluginName("@scope/[email protected]")).toBe("@scope/pkg")
  1430. expect(Config.getPluginName("@opencode/[email protected]")).toBe("@opencode/plugin")
  1431. })
  1432. test("returns full string for package without version", () => {
  1433. expect(Config.getPluginName("some-plugin")).toBe("some-plugin")
  1434. expect(Config.getPluginName("@scope/pkg")).toBe("@scope/pkg")
  1435. })
  1436. })
  1437. describe("deduplicatePlugins", () => {
  1438. test("removes duplicates keeping higher priority (later entries)", () => {
  1439. const plugins = ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]
  1440. const result = Config.deduplicatePlugins(plugins)
  1441. expect(result).toContain("[email protected]")
  1442. expect(result).toContain("[email protected]")
  1443. expect(result).toContain("[email protected]")
  1444. expect(result).not.toContain("[email protected]")
  1445. expect(result.length).toBe(3)
  1446. })
  1447. test("prefers local file over npm package with same name", () => {
  1448. const plugins = ["[email protected]", "file:///project/.opencode/plugin/oh-my-opencode.js"]
  1449. const result = Config.deduplicatePlugins(plugins)
  1450. expect(result.length).toBe(1)
  1451. expect(result[0]).toBe("file:///project/.opencode/plugin/oh-my-opencode.js")
  1452. })
  1453. test("preserves order of remaining plugins", () => {
  1454. const plugins = ["[email protected]", "[email protected]", "[email protected]"]
  1455. const result = Config.deduplicatePlugins(plugins)
  1456. expect(result).toEqual(["[email protected]", "[email protected]", "[email protected]"])
  1457. })
  1458. test("local plugin directory overrides global opencode.json plugin", async () => {
  1459. await using tmp = await tmpdir({
  1460. init: async (dir) => {
  1461. const projectDir = path.join(dir, "project")
  1462. const opencodeDir = path.join(projectDir, ".opencode")
  1463. const pluginDir = path.join(opencodeDir, "plugin")
  1464. await fs.mkdir(pluginDir, { recursive: true })
  1465. await Filesystem.write(
  1466. path.join(dir, "opencode.json"),
  1467. JSON.stringify({
  1468. $schema: "https://opencode.ai/config.json",
  1469. plugin: ["[email protected]"],
  1470. }),
  1471. )
  1472. await Filesystem.write(path.join(pluginDir, "my-plugin.js"), "export default {}")
  1473. },
  1474. })
  1475. await Instance.provide({
  1476. directory: path.join(tmp.path, "project"),
  1477. fn: async () => {
  1478. const config = await Config.get()
  1479. const plugins = config.plugin ?? []
  1480. const myPlugins = plugins.filter((p) => Config.getPluginName(p) === "my-plugin")
  1481. expect(myPlugins.length).toBe(1)
  1482. expect(myPlugins[0].startsWith("file://")).toBe(true)
  1483. },
  1484. })
  1485. })
  1486. })
  1487. describe("OPENCODE_DISABLE_PROJECT_CONFIG", () => {
  1488. test("skips project config files when flag is set", async () => {
  1489. const originalEnv = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1490. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  1491. try {
  1492. await using tmp = await tmpdir({
  1493. init: async (dir) => {
  1494. // Create a project config that would normally be loaded
  1495. await Filesystem.write(
  1496. path.join(dir, "opencode.json"),
  1497. JSON.stringify({
  1498. $schema: "https://opencode.ai/config.json",
  1499. model: "project/model",
  1500. username: "project-user",
  1501. }),
  1502. )
  1503. },
  1504. })
  1505. await Instance.provide({
  1506. directory: tmp.path,
  1507. fn: async () => {
  1508. const config = await Config.get()
  1509. // Project config should NOT be loaded - model should be default, not "project/model"
  1510. expect(config.model).not.toBe("project/model")
  1511. expect(config.username).not.toBe("project-user")
  1512. },
  1513. })
  1514. } finally {
  1515. if (originalEnv === undefined) {
  1516. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1517. } else {
  1518. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalEnv
  1519. }
  1520. }
  1521. })
  1522. test("skips project .opencode/ directories when flag is set", async () => {
  1523. const originalEnv = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1524. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  1525. try {
  1526. await using tmp = await tmpdir({
  1527. init: async (dir) => {
  1528. // Create a .opencode directory with a command
  1529. const opencodeDir = path.join(dir, ".opencode", "command")
  1530. await fs.mkdir(opencodeDir, { recursive: true })
  1531. await Filesystem.write(path.join(opencodeDir, "test-cmd.md"), "# Test Command\nThis is a test command.")
  1532. },
  1533. })
  1534. await Instance.provide({
  1535. directory: tmp.path,
  1536. fn: async () => {
  1537. const directories = await Config.directories()
  1538. // Project .opencode should NOT be in directories list
  1539. const hasProjectOpencode = directories.some((d) => d.startsWith(tmp.path))
  1540. expect(hasProjectOpencode).toBe(false)
  1541. },
  1542. })
  1543. } finally {
  1544. if (originalEnv === undefined) {
  1545. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1546. } else {
  1547. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalEnv
  1548. }
  1549. }
  1550. })
  1551. test("still loads global config when flag is set", async () => {
  1552. const originalEnv = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1553. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  1554. try {
  1555. await using tmp = await tmpdir()
  1556. await Instance.provide({
  1557. directory: tmp.path,
  1558. fn: async () => {
  1559. // Should still get default config (from global or defaults)
  1560. const config = await Config.get()
  1561. expect(config).toBeDefined()
  1562. expect(config.username).toBeDefined()
  1563. },
  1564. })
  1565. } finally {
  1566. if (originalEnv === undefined) {
  1567. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1568. } else {
  1569. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalEnv
  1570. }
  1571. }
  1572. })
  1573. test("skips relative instructions with warning when flag is set but no config dir", async () => {
  1574. const originalDisable = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1575. const originalConfigDir = process.env["OPENCODE_CONFIG_DIR"]
  1576. try {
  1577. // Ensure no config dir is set
  1578. delete process.env["OPENCODE_CONFIG_DIR"]
  1579. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  1580. await using tmp = await tmpdir({
  1581. init: async (dir) => {
  1582. // Create a config with relative instruction path
  1583. await Filesystem.write(
  1584. path.join(dir, "opencode.json"),
  1585. JSON.stringify({
  1586. $schema: "https://opencode.ai/config.json",
  1587. instructions: ["./CUSTOM.md"],
  1588. }),
  1589. )
  1590. // Create the instruction file (should be skipped)
  1591. await Filesystem.write(path.join(dir, "CUSTOM.md"), "# Custom Instructions")
  1592. },
  1593. })
  1594. await Instance.provide({
  1595. directory: tmp.path,
  1596. fn: async () => {
  1597. // The relative instruction should be skipped without error
  1598. // We're mainly verifying this doesn't throw and the config loads
  1599. const config = await Config.get()
  1600. expect(config).toBeDefined()
  1601. // The instruction should have been skipped (warning logged)
  1602. // We can't easily test the warning was logged, but we verify
  1603. // the relative path didn't cause an error
  1604. },
  1605. })
  1606. } finally {
  1607. if (originalDisable === undefined) {
  1608. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1609. } else {
  1610. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalDisable
  1611. }
  1612. if (originalConfigDir === undefined) {
  1613. delete process.env["OPENCODE_CONFIG_DIR"]
  1614. } else {
  1615. process.env["OPENCODE_CONFIG_DIR"] = originalConfigDir
  1616. }
  1617. }
  1618. })
  1619. test("OPENCODE_CONFIG_DIR still works when flag is set", async () => {
  1620. const originalDisable = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1621. const originalConfigDir = process.env["OPENCODE_CONFIG_DIR"]
  1622. try {
  1623. await using configDirTmp = await tmpdir({
  1624. init: async (dir) => {
  1625. // Create config in the custom config dir
  1626. await Filesystem.write(
  1627. path.join(dir, "opencode.json"),
  1628. JSON.stringify({
  1629. $schema: "https://opencode.ai/config.json",
  1630. model: "configdir/model",
  1631. }),
  1632. )
  1633. },
  1634. })
  1635. await using projectTmp = await tmpdir({
  1636. init: async (dir) => {
  1637. // Create config in project (should be ignored)
  1638. await Filesystem.write(
  1639. path.join(dir, "opencode.json"),
  1640. JSON.stringify({
  1641. $schema: "https://opencode.ai/config.json",
  1642. model: "project/model",
  1643. }),
  1644. )
  1645. },
  1646. })
  1647. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  1648. process.env["OPENCODE_CONFIG_DIR"] = configDirTmp.path
  1649. await Instance.provide({
  1650. directory: projectTmp.path,
  1651. fn: async () => {
  1652. const config = await Config.get()
  1653. // Should load from OPENCODE_CONFIG_DIR, not project
  1654. expect(config.model).toBe("configdir/model")
  1655. },
  1656. })
  1657. } finally {
  1658. if (originalDisable === undefined) {
  1659. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1660. } else {
  1661. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalDisable
  1662. }
  1663. if (originalConfigDir === undefined) {
  1664. delete process.env["OPENCODE_CONFIG_DIR"]
  1665. } else {
  1666. process.env["OPENCODE_CONFIG_DIR"] = originalConfigDir
  1667. }
  1668. }
  1669. })
  1670. })
  1671. describe("OPENCODE_CONFIG_CONTENT token substitution", () => {
  1672. test("substitutes {env:} tokens in OPENCODE_CONFIG_CONTENT", async () => {
  1673. const originalEnv = process.env["OPENCODE_CONFIG_CONTENT"]
  1674. const originalTestVar = process.env["TEST_CONFIG_VAR"]
  1675. process.env["TEST_CONFIG_VAR"] = "test_api_key_12345"
  1676. process.env["OPENCODE_CONFIG_CONTENT"] = JSON.stringify({
  1677. $schema: "https://opencode.ai/config.json",
  1678. username: "{env:TEST_CONFIG_VAR}",
  1679. })
  1680. try {
  1681. await using tmp = await tmpdir()
  1682. await Instance.provide({
  1683. directory: tmp.path,
  1684. fn: async () => {
  1685. const config = await Config.get()
  1686. expect(config.username).toBe("test_api_key_12345")
  1687. },
  1688. })
  1689. } finally {
  1690. if (originalEnv !== undefined) {
  1691. process.env["OPENCODE_CONFIG_CONTENT"] = originalEnv
  1692. } else {
  1693. delete process.env["OPENCODE_CONFIG_CONTENT"]
  1694. }
  1695. if (originalTestVar !== undefined) {
  1696. process.env["TEST_CONFIG_VAR"] = originalTestVar
  1697. } else {
  1698. delete process.env["TEST_CONFIG_VAR"]
  1699. }
  1700. }
  1701. })
  1702. test("substitutes {file:} tokens in OPENCODE_CONFIG_CONTENT", async () => {
  1703. const originalEnv = process.env["OPENCODE_CONFIG_CONTENT"]
  1704. try {
  1705. await using tmp = await tmpdir({
  1706. init: async (dir) => {
  1707. await Filesystem.write(path.join(dir, "api_key.txt"), "secret_key_from_file")
  1708. process.env["OPENCODE_CONFIG_CONTENT"] = JSON.stringify({
  1709. $schema: "https://opencode.ai/config.json",
  1710. username: "{file:./api_key.txt}",
  1711. })
  1712. },
  1713. })
  1714. await Instance.provide({
  1715. directory: tmp.path,
  1716. fn: async () => {
  1717. const config = await Config.get()
  1718. expect(config.username).toBe("secret_key_from_file")
  1719. },
  1720. })
  1721. } finally {
  1722. if (originalEnv !== undefined) {
  1723. process.env["OPENCODE_CONFIG_CONTENT"] = originalEnv
  1724. } else {
  1725. delete process.env["OPENCODE_CONFIG_CONTENT"]
  1726. }
  1727. }
  1728. })
  1729. })