config.test.ts 56 KB

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