config.test.ts 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570
  1. import { test, expect, describe, mock, afterEach, beforeEach } from "bun:test"
  2. import { Effect, Layer, Option } from "effect"
  3. import { NodeFileSystem, NodePath } from "@effect/platform-node"
  4. import { Config } from "@/config/config"
  5. import { ConfigManaged } from "@/config/managed"
  6. import { ConfigParse } from "../../src/config/parse"
  7. import { EffectFlock } from "@opencode-ai/core/util/effect-flock"
  8. import { Instance } from "../../src/project/instance"
  9. import { WithInstance } from "../../src/project/with-instance"
  10. import { Auth } from "../../src/auth"
  11. import { Account } from "../../src/account/account"
  12. import { AccessToken, AccountID, OrgID } from "../../src/account/schema"
  13. import { AppFileSystem } from "@opencode-ai/core/filesystem"
  14. import { Env } from "../../src/env"
  15. import { provideTestInstance, provideTmpdirInstance } from "../fixture/fixture"
  16. import { tmpdir } from "../fixture/fixture"
  17. import { InstanceRuntime } from "@/project/instance-runtime"
  18. import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
  19. import { testEffect } from "../lib/effect"
  20. /** Infra layer that provides FileSystem, Path, ChildProcessSpawner for test fixtures */
  21. const infra = CrossSpawnSpawner.defaultLayer.pipe(
  22. Layer.provideMerge(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer)),
  23. )
  24. import path from "path"
  25. import fs from "fs/promises"
  26. import { pathToFileURL } from "url"
  27. import { Global } from "@opencode-ai/core/global"
  28. import { ProjectID } from "../../src/project/schema"
  29. import { Filesystem } from "@/util/filesystem"
  30. import { ConfigPlugin } from "@/config/plugin"
  31. import { Npm } from "@opencode-ai/core/npm"
  32. const emptyAccount = Layer.mock(Account.Service)({
  33. active: () => Effect.succeed(Option.none()),
  34. activeOrg: () => Effect.succeed(Option.none()),
  35. })
  36. const emptyAuth = Layer.mock(Auth.Service)({
  37. all: () => Effect.succeed({}),
  38. })
  39. const testFlock = EffectFlock.defaultLayer
  40. const noopNpm = Layer.mock(Npm.Service)({
  41. install: () => Effect.void,
  42. add: () => Effect.die("not implemented"),
  43. which: () => Effect.succeed(Option.none()),
  44. })
  45. const layer = Config.layer.pipe(
  46. Layer.provide(testFlock),
  47. Layer.provide(AppFileSystem.defaultLayer),
  48. Layer.provide(Env.defaultLayer),
  49. Layer.provide(emptyAuth),
  50. Layer.provide(emptyAccount),
  51. Layer.provideMerge(infra),
  52. Layer.provide(noopNpm),
  53. )
  54. const it = testEffect(layer)
  55. const load = () => Effect.runPromise(Config.Service.use((svc) => svc.get()).pipe(Effect.scoped, Effect.provide(layer)))
  56. const save = (config: Config.Info) =>
  57. Effect.runPromise(Config.Service.use((svc) => svc.update(config)).pipe(Effect.scoped, Effect.provide(layer)))
  58. const saveGlobal = (config: Config.Info) =>
  59. Effect.runPromise(
  60. Config.Service.use((svc) => svc.updateGlobal(config)).pipe(
  61. Effect.map((result) => result.info),
  62. Effect.scoped,
  63. Effect.provide(layer),
  64. ),
  65. )
  66. const clear = async (wait = false) => {
  67. await Effect.runPromise(Config.Service.use((svc) => svc.invalidate()).pipe(Effect.scoped, Effect.provide(layer)))
  68. if (wait) await InstanceRuntime.disposeAllInstances()
  69. }
  70. const listDirs = () =>
  71. Effect.runPromise(Config.Service.use((svc) => svc.directories()).pipe(Effect.scoped, Effect.provide(layer)))
  72. const ready = () =>
  73. Effect.runPromise(Config.Service.use((svc) => svc.waitForDependencies()).pipe(Effect.scoped, Effect.provide(layer)))
  74. // Get managed config directory from environment (set in preload.ts)
  75. const managedConfigDir = process.env.OPENCODE_TEST_MANAGED_CONFIG_DIR!
  76. beforeEach(async () => {
  77. await clear(true)
  78. })
  79. afterEach(async () => {
  80. await fs.rm(managedConfigDir, { force: true, recursive: true }).catch(() => {})
  81. await clear(true)
  82. })
  83. async function writeManagedSettings(settings: object, filename = "opencode.json") {
  84. await fs.mkdir(managedConfigDir, { recursive: true })
  85. await Filesystem.write(path.join(managedConfigDir, filename), JSON.stringify(settings))
  86. }
  87. async function writeConfig(dir: string, config: object, name = "opencode.json") {
  88. await Filesystem.write(path.join(dir, name), JSON.stringify(config))
  89. }
  90. async function check(map: (dir: string) => string) {
  91. if (process.platform !== "win32") return
  92. await using globalTmp = await tmpdir()
  93. await using tmp = await tmpdir({ git: true, config: { snapshot: true } })
  94. const prev = Global.Path.config
  95. ;(Global.Path as { config: string }).config = globalTmp.path
  96. await clear()
  97. try {
  98. await writeConfig(globalTmp.path, {
  99. $schema: "https://opencode.ai/config.json",
  100. snapshot: false,
  101. })
  102. await WithInstance.provide({
  103. directory: map(tmp.path),
  104. fn: async () => {
  105. const cfg = await load()
  106. expect(cfg.snapshot).toBe(true)
  107. expect(Instance.directory).toBe(Filesystem.resolve(tmp.path))
  108. expect(Instance.project.id).not.toBe(ProjectID.global)
  109. },
  110. })
  111. } finally {
  112. await InstanceRuntime.disposeAllInstances()
  113. ;(Global.Path as { config: string }).config = prev
  114. await clear()
  115. }
  116. }
  117. test("loads config with defaults when no files exist", async () => {
  118. await using tmp = await tmpdir()
  119. await WithInstance.provide({
  120. directory: tmp.path,
  121. fn: async () => {
  122. const config = await load()
  123. expect(config.username).toBeDefined()
  124. },
  125. })
  126. })
  127. test("loads JSON config file", async () => {
  128. await using tmp = await tmpdir({
  129. init: async (dir) => {
  130. await writeConfig(dir, {
  131. $schema: "https://opencode.ai/config.json",
  132. model: "test/model",
  133. username: "testuser",
  134. })
  135. },
  136. })
  137. await WithInstance.provide({
  138. directory: tmp.path,
  139. fn: async () => {
  140. const config = await load()
  141. expect(config.model).toBe("test/model")
  142. expect(config.username).toBe("testuser")
  143. },
  144. })
  145. })
  146. test("loads shell config field", async () => {
  147. await using tmp = await tmpdir({
  148. init: async (dir) => {
  149. await writeConfig(dir, {
  150. $schema: "https://opencode.ai/config.json",
  151. shell: "bash",
  152. })
  153. },
  154. })
  155. await WithInstance.provide({
  156. directory: tmp.path,
  157. fn: async () => {
  158. const config = await load()
  159. expect(config.shell).toBe("bash")
  160. },
  161. })
  162. })
  163. test("updates config and preserves empty shell sentinel", async () => {
  164. await using tmp = await tmpdir({
  165. init: async (dir) => {
  166. await writeConfig(
  167. dir,
  168. {
  169. $schema: "https://opencode.ai/config.json",
  170. shell: "bash",
  171. },
  172. "config.json",
  173. )
  174. },
  175. })
  176. await WithInstance.provide({
  177. directory: tmp.path,
  178. fn: async () => {
  179. await save({ shell: "" })
  180. const writtenConfig = await Filesystem.readJson<{ shell?: string }>(path.join(tmp.path, "config.json"))
  181. expect(writtenConfig.shell).toBe("")
  182. },
  183. })
  184. })
  185. test("updates global config and omits empty shell key in json", async () => {
  186. await using tmp = await tmpdir({
  187. init: async (dir) => {
  188. await writeConfig(dir, {
  189. $schema: "https://opencode.ai/config.json",
  190. shell: "bash",
  191. })
  192. },
  193. })
  194. const prev = Global.Path.config
  195. ;(Global.Path as { config: string }).config = tmp.path
  196. await clear(true)
  197. try {
  198. await saveGlobal({ shell: "" })
  199. const writtenConfig = await Filesystem.readJson<{ shell?: string }>(path.join(tmp.path, "opencode.json"))
  200. expect("shell" in writtenConfig).toBe(false)
  201. } finally {
  202. ;(Global.Path as { config: string }).config = prev
  203. await clear(true)
  204. }
  205. })
  206. test("updates global config and omits empty shell key in jsonc", async () => {
  207. await using tmp = await tmpdir({
  208. init: async (dir) => {
  209. await Filesystem.write(
  210. path.join(dir, "opencode.jsonc"),
  211. JSON.stringify({
  212. $schema: "https://opencode.ai/config.json",
  213. shell: "bash",
  214. model: "test/model",
  215. }),
  216. )
  217. },
  218. })
  219. const prev = Global.Path.config
  220. ;(Global.Path as { config: string }).config = tmp.path
  221. await clear(true)
  222. try {
  223. await saveGlobal({ shell: "" })
  224. const file = path.join(tmp.path, "opencode.jsonc")
  225. const writtenConfig = await Filesystem.readText(file)
  226. const parsed = ConfigParse.schema(Config.Info.zod, ConfigParse.jsonc(writtenConfig, file), file)
  227. expect(writtenConfig).not.toContain('"shell"')
  228. expect(parsed.shell).toBeUndefined()
  229. expect(parsed.model).toBe("test/model")
  230. } finally {
  231. ;(Global.Path as { config: string }).config = prev
  232. await clear(true)
  233. }
  234. })
  235. test("loads formatter boolean config", async () => {
  236. await using tmp = await tmpdir({
  237. init: async (dir) => {
  238. await writeConfig(dir, {
  239. $schema: "https://opencode.ai/config.json",
  240. formatter: true,
  241. })
  242. },
  243. })
  244. await WithInstance.provide({
  245. directory: tmp.path,
  246. fn: async () => {
  247. const config = await load()
  248. expect(config.formatter).toBe(true)
  249. },
  250. })
  251. })
  252. test("loads lsp boolean config", async () => {
  253. await using tmp = await tmpdir({
  254. init: async (dir) => {
  255. await writeConfig(dir, {
  256. $schema: "https://opencode.ai/config.json",
  257. lsp: true,
  258. })
  259. },
  260. })
  261. await WithInstance.provide({
  262. directory: tmp.path,
  263. fn: async () => {
  264. const config = await load()
  265. expect(config.lsp).toBe(true)
  266. },
  267. })
  268. })
  269. test("loads project config from Git Bash and MSYS2 paths on Windows", async () => {
  270. // Git Bash and MSYS2 both use /<drive>/... paths on Windows.
  271. await check((dir) => {
  272. const drive = dir[0].toLowerCase()
  273. const rest = dir.slice(2).replaceAll("\\", "/")
  274. return `/${drive}${rest}`
  275. })
  276. })
  277. test("loads project config from Cygwin paths on Windows", async () => {
  278. await check((dir) => {
  279. const drive = dir[0].toLowerCase()
  280. const rest = dir.slice(2).replaceAll("\\", "/")
  281. return `/cygdrive/${drive}${rest}`
  282. })
  283. })
  284. test("ignores legacy tui keys in opencode config", async () => {
  285. await using tmp = await tmpdir({
  286. init: async (dir) => {
  287. await writeConfig(dir, {
  288. $schema: "https://opencode.ai/config.json",
  289. model: "test/model",
  290. theme: "legacy",
  291. tui: { scroll_speed: 4 },
  292. })
  293. },
  294. })
  295. await WithInstance.provide({
  296. directory: tmp.path,
  297. fn: async () => {
  298. const config = await load()
  299. expect(config.model).toBe("test/model")
  300. expect((config as Record<string, unknown>).theme).toBeUndefined()
  301. expect((config as Record<string, unknown>).tui).toBeUndefined()
  302. },
  303. })
  304. })
  305. test("loads JSONC config file", async () => {
  306. await using tmp = await tmpdir({
  307. init: async (dir) => {
  308. await Filesystem.write(
  309. path.join(dir, "opencode.jsonc"),
  310. `{
  311. // This is a comment
  312. "$schema": "https://opencode.ai/config.json",
  313. "model": "test/model",
  314. "username": "testuser"
  315. }`,
  316. )
  317. },
  318. })
  319. await WithInstance.provide({
  320. directory: tmp.path,
  321. fn: async () => {
  322. const config = await load()
  323. expect(config.model).toBe("test/model")
  324. expect(config.username).toBe("testuser")
  325. },
  326. })
  327. })
  328. test("jsonc overrides json in the same directory", async () => {
  329. await using tmp = await tmpdir({
  330. init: async (dir) => {
  331. await writeConfig(
  332. dir,
  333. {
  334. $schema: "https://opencode.ai/config.json",
  335. model: "base",
  336. username: "base",
  337. },
  338. "opencode.jsonc",
  339. )
  340. await writeConfig(dir, {
  341. $schema: "https://opencode.ai/config.json",
  342. model: "override",
  343. })
  344. },
  345. })
  346. await WithInstance.provide({
  347. directory: tmp.path,
  348. fn: async () => {
  349. const config = await load()
  350. expect(config.model).toBe("base")
  351. expect(config.username).toBe("base")
  352. },
  353. })
  354. })
  355. test("handles environment variable substitution", async () => {
  356. const originalEnv = process.env["TEST_VAR"]
  357. process.env["TEST_VAR"] = "test-user"
  358. try {
  359. await using tmp = await tmpdir({
  360. init: async (dir) => {
  361. await writeConfig(dir, {
  362. $schema: "https://opencode.ai/config.json",
  363. username: "{env:TEST_VAR}",
  364. })
  365. },
  366. })
  367. await WithInstance.provide({
  368. directory: tmp.path,
  369. fn: async () => {
  370. const config = await load()
  371. expect(config.username).toBe("test-user")
  372. },
  373. })
  374. } finally {
  375. if (originalEnv !== undefined) {
  376. process.env["TEST_VAR"] = originalEnv
  377. } else {
  378. delete process.env["TEST_VAR"]
  379. }
  380. }
  381. })
  382. test("preserves env variables when adding $schema to config", async () => {
  383. const originalEnv = process.env["PRESERVE_VAR"]
  384. process.env["PRESERVE_VAR"] = "secret_value"
  385. try {
  386. await using tmp = await tmpdir({
  387. init: async (dir) => {
  388. // Config without $schema - should trigger auto-add
  389. await Filesystem.write(
  390. path.join(dir, "opencode.json"),
  391. JSON.stringify({
  392. username: "{env:PRESERVE_VAR}",
  393. }),
  394. )
  395. },
  396. })
  397. await WithInstance.provide({
  398. directory: tmp.path,
  399. fn: async () => {
  400. const config = await load()
  401. expect(config.username).toBe("secret_value")
  402. // Read the file to verify the env variable was preserved
  403. const content = await Filesystem.readText(path.join(tmp.path, "opencode.json"))
  404. expect(content).toContain("{env:PRESERVE_VAR}")
  405. expect(content).not.toContain("secret_value")
  406. expect(content).toContain("$schema")
  407. },
  408. })
  409. } finally {
  410. if (originalEnv !== undefined) {
  411. process.env["PRESERVE_VAR"] = originalEnv
  412. } else {
  413. delete process.env["PRESERVE_VAR"]
  414. }
  415. }
  416. })
  417. test("resolves env templates in account config with account token", async () => {
  418. const originalControlToken = process.env["OPENCODE_CONSOLE_TOKEN"]
  419. const fakeAccount = Layer.mock(Account.Service)({
  420. active: () =>
  421. Effect.succeed(
  422. Option.some({
  423. id: AccountID.make("account-1"),
  424. email: "user@example.com",
  425. url: "https://control.example.com",
  426. active_org_id: OrgID.make("org-1"),
  427. }),
  428. ),
  429. activeOrg: () =>
  430. Effect.succeed(
  431. Option.some({
  432. account: {
  433. id: AccountID.make("account-1"),
  434. email: "user@example.com",
  435. url: "https://control.example.com",
  436. active_org_id: OrgID.make("org-1"),
  437. },
  438. org: {
  439. id: OrgID.make("org-1"),
  440. name: "Example Org",
  441. },
  442. }),
  443. ),
  444. config: () =>
  445. Effect.succeed(
  446. Option.some({
  447. provider: { opencode: { options: { apiKey: "{env:OPENCODE_CONSOLE_TOKEN}" } } },
  448. }),
  449. ),
  450. token: () => Effect.succeed(Option.some(AccessToken.make("st_test_token"))),
  451. })
  452. const layer = Config.layer.pipe(
  453. Layer.provide(testFlock),
  454. Layer.provide(AppFileSystem.defaultLayer),
  455. Layer.provide(Env.defaultLayer),
  456. Layer.provide(emptyAuth),
  457. Layer.provide(fakeAccount),
  458. Layer.provideMerge(infra),
  459. Layer.provide(noopNpm),
  460. )
  461. try {
  462. await provideTmpdirInstance(() =>
  463. Config.Service.use((svc) =>
  464. Effect.gen(function* () {
  465. const config = yield* svc.get()
  466. expect(config.provider?.["opencode"]?.options?.apiKey).toBe("st_test_token")
  467. }),
  468. ),
  469. ).pipe(Effect.scoped, Effect.provide(layer), Effect.runPromise)
  470. } finally {
  471. if (originalControlToken !== undefined) {
  472. process.env["OPENCODE_CONSOLE_TOKEN"] = originalControlToken
  473. } else {
  474. delete process.env["OPENCODE_CONSOLE_TOKEN"]
  475. }
  476. }
  477. })
  478. test("handles file inclusion substitution", async () => {
  479. await using tmp = await tmpdir({
  480. init: async (dir) => {
  481. await Filesystem.write(path.join(dir, "included.txt"), "test-user")
  482. await writeConfig(dir, {
  483. $schema: "https://opencode.ai/config.json",
  484. username: "{file:included.txt}",
  485. })
  486. },
  487. })
  488. await WithInstance.provide({
  489. directory: tmp.path,
  490. fn: async () => {
  491. const config = await load()
  492. expect(config.username).toBe("test-user")
  493. },
  494. })
  495. })
  496. test("handles file inclusion with replacement tokens", async () => {
  497. await using tmp = await tmpdir({
  498. init: async (dir) => {
  499. await Filesystem.write(path.join(dir, "included.md"), "const out = await Bun.$`echo hi`")
  500. await writeConfig(dir, {
  501. $schema: "https://opencode.ai/config.json",
  502. username: "{file:included.md}",
  503. })
  504. },
  505. })
  506. await WithInstance.provide({
  507. directory: tmp.path,
  508. fn: async () => {
  509. const config = await load()
  510. expect(config.username).toBe("const out = await Bun.$`echo hi`")
  511. },
  512. })
  513. })
  514. test("validates config schema and throws on invalid fields", async () => {
  515. await using tmp = await tmpdir({
  516. init: async (dir) => {
  517. await writeConfig(dir, {
  518. $schema: "https://opencode.ai/config.json",
  519. invalid_field: "should cause error",
  520. })
  521. },
  522. })
  523. await provideTestInstance({
  524. directory: tmp.path,
  525. fn: async () => {
  526. // Strict schema should throw an error for invalid fields
  527. await expect(load()).rejects.toThrow()
  528. },
  529. })
  530. })
  531. test("throws error for invalid JSON", async () => {
  532. await using tmp = await tmpdir({
  533. init: async (dir) => {
  534. await Filesystem.write(path.join(dir, "opencode.json"), "{ invalid json }")
  535. },
  536. })
  537. await provideTestInstance({
  538. directory: tmp.path,
  539. fn: async () => {
  540. await expect(load()).rejects.toThrow()
  541. },
  542. })
  543. })
  544. test("handles agent configuration", async () => {
  545. await using tmp = await tmpdir({
  546. init: async (dir) => {
  547. await writeConfig(dir, {
  548. $schema: "https://opencode.ai/config.json",
  549. agent: {
  550. test_agent: {
  551. model: "test/model",
  552. temperature: 0.7,
  553. description: "test agent",
  554. },
  555. },
  556. })
  557. },
  558. })
  559. await WithInstance.provide({
  560. directory: tmp.path,
  561. fn: async () => {
  562. const config = await load()
  563. expect(config.agent?.["test_agent"]).toEqual(
  564. expect.objectContaining({
  565. model: "test/model",
  566. temperature: 0.7,
  567. description: "test agent",
  568. }),
  569. )
  570. },
  571. })
  572. })
  573. test("treats agent variant as model-scoped setting (not provider option)", async () => {
  574. await using tmp = await tmpdir({
  575. init: async (dir) => {
  576. await writeConfig(dir, {
  577. $schema: "https://opencode.ai/config.json",
  578. agent: {
  579. test_agent: {
  580. model: "openai/gpt-5.2",
  581. variant: "xhigh",
  582. max_tokens: 123,
  583. },
  584. },
  585. })
  586. },
  587. })
  588. await WithInstance.provide({
  589. directory: tmp.path,
  590. fn: async () => {
  591. const config = await load()
  592. const agent = config.agent?.["test_agent"]
  593. expect(agent?.variant).toBe("xhigh")
  594. expect(agent?.options).toMatchObject({
  595. max_tokens: 123,
  596. })
  597. expect(agent?.options).not.toHaveProperty("variant")
  598. },
  599. })
  600. })
  601. test("handles command configuration", async () => {
  602. await using tmp = await tmpdir({
  603. init: async (dir) => {
  604. await writeConfig(dir, {
  605. $schema: "https://opencode.ai/config.json",
  606. command: {
  607. test_command: {
  608. template: "test template",
  609. description: "test command",
  610. agent: "test_agent",
  611. },
  612. },
  613. })
  614. },
  615. })
  616. await WithInstance.provide({
  617. directory: tmp.path,
  618. fn: async () => {
  619. const config = await load()
  620. expect(config.command?.["test_command"]).toEqual({
  621. template: "test template",
  622. description: "test command",
  623. agent: "test_agent",
  624. })
  625. },
  626. })
  627. })
  628. test("migrates autoshare to share field", async () => {
  629. await using tmp = await tmpdir({
  630. init: async (dir) => {
  631. await Filesystem.write(
  632. path.join(dir, "opencode.json"),
  633. JSON.stringify({
  634. $schema: "https://opencode.ai/config.json",
  635. autoshare: true,
  636. }),
  637. )
  638. },
  639. })
  640. await WithInstance.provide({
  641. directory: tmp.path,
  642. fn: async () => {
  643. const config = await load()
  644. expect(config.share).toBe("auto")
  645. expect(config.autoshare).toBe(true)
  646. },
  647. })
  648. })
  649. test("migrates mode field to agent field", async () => {
  650. await using tmp = await tmpdir({
  651. init: async (dir) => {
  652. await Filesystem.write(
  653. path.join(dir, "opencode.json"),
  654. JSON.stringify({
  655. $schema: "https://opencode.ai/config.json",
  656. mode: {
  657. test_mode: {
  658. model: "test/model",
  659. temperature: 0.5,
  660. },
  661. },
  662. }),
  663. )
  664. },
  665. })
  666. await WithInstance.provide({
  667. directory: tmp.path,
  668. fn: async () => {
  669. const config = await load()
  670. expect(config.agent?.["test_mode"]).toEqual({
  671. model: "test/model",
  672. temperature: 0.5,
  673. mode: "primary",
  674. options: {},
  675. permission: {},
  676. })
  677. },
  678. })
  679. })
  680. test("loads config from .opencode directory", async () => {
  681. await using tmp = await tmpdir({
  682. init: async (dir) => {
  683. const opencodeDir = path.join(dir, ".opencode")
  684. await fs.mkdir(opencodeDir, { recursive: true })
  685. const agentDir = path.join(opencodeDir, "agent")
  686. await fs.mkdir(agentDir, { recursive: true })
  687. await Filesystem.write(
  688. path.join(agentDir, "test.md"),
  689. `---
  690. model: test/model
  691. ---
  692. Test agent prompt`,
  693. )
  694. },
  695. })
  696. await WithInstance.provide({
  697. directory: tmp.path,
  698. fn: async () => {
  699. const config = await load()
  700. expect(config.agent?.["test"]).toEqual(
  701. expect.objectContaining({
  702. name: "test",
  703. model: "test/model",
  704. prompt: "Test agent prompt",
  705. }),
  706. )
  707. },
  708. })
  709. })
  710. test("agent markdown permission config preserves user key order", async () => {
  711. await using tmp = await tmpdir({
  712. init: async (dir) => {
  713. const agentDir = path.join(dir, ".opencode", "agent")
  714. await fs.mkdir(agentDir, { recursive: true })
  715. await Filesystem.write(
  716. path.join(agentDir, "ordered.md"),
  717. `---
  718. permission:
  719. bash: allow
  720. "*": deny
  721. edit: ask
  722. ---
  723. Ordered permissions`,
  724. )
  725. },
  726. })
  727. await WithInstance.provide({
  728. directory: tmp.path,
  729. fn: async () => {
  730. const config = await load()
  731. expect(Object.keys(config.agent?.ordered?.permission ?? {})).toEqual(["bash", "*", "edit"])
  732. },
  733. })
  734. })
  735. test("loads agents from .opencode/agents (plural)", async () => {
  736. await using tmp = await tmpdir({
  737. init: async (dir) => {
  738. const opencodeDir = path.join(dir, ".opencode")
  739. await fs.mkdir(opencodeDir, { recursive: true })
  740. const agentsDir = path.join(opencodeDir, "agents")
  741. await fs.mkdir(path.join(agentsDir, "nested"), { recursive: true })
  742. await Filesystem.write(
  743. path.join(agentsDir, "helper.md"),
  744. `---
  745. model: test/model
  746. mode: subagent
  747. ---
  748. Helper agent prompt`,
  749. )
  750. await Filesystem.write(
  751. path.join(agentsDir, "nested", "child.md"),
  752. `---
  753. model: test/model
  754. mode: subagent
  755. ---
  756. Nested agent prompt`,
  757. )
  758. },
  759. })
  760. await WithInstance.provide({
  761. directory: tmp.path,
  762. fn: async () => {
  763. const config = await load()
  764. expect(config.agent?.["helper"]).toMatchObject({
  765. name: "helper",
  766. model: "test/model",
  767. mode: "subagent",
  768. prompt: "Helper agent prompt",
  769. })
  770. expect(config.agent?.["nested/child"]).toMatchObject({
  771. name: "nested/child",
  772. model: "test/model",
  773. mode: "subagent",
  774. prompt: "Nested agent prompt",
  775. })
  776. },
  777. })
  778. })
  779. test("loads commands from .opencode/command (singular)", async () => {
  780. await using tmp = await tmpdir({
  781. init: async (dir) => {
  782. const opencodeDir = path.join(dir, ".opencode")
  783. await fs.mkdir(opencodeDir, { recursive: true })
  784. const commandDir = path.join(opencodeDir, "command")
  785. await fs.mkdir(path.join(commandDir, "nested"), { recursive: true })
  786. await Filesystem.write(
  787. path.join(commandDir, "hello.md"),
  788. `---
  789. description: Test command
  790. ---
  791. Hello from singular command`,
  792. )
  793. await Filesystem.write(
  794. path.join(commandDir, "nested", "child.md"),
  795. `---
  796. description: Nested command
  797. ---
  798. Nested command template`,
  799. )
  800. },
  801. })
  802. await WithInstance.provide({
  803. directory: tmp.path,
  804. fn: async () => {
  805. const config = await load()
  806. expect(config.command?.["hello"]).toEqual({
  807. description: "Test command",
  808. template: "Hello from singular command",
  809. })
  810. expect(config.command?.["nested/child"]).toEqual({
  811. description: "Nested command",
  812. template: "Nested command template",
  813. })
  814. },
  815. })
  816. })
  817. test("loads commands from .opencode/commands (plural)", async () => {
  818. await using tmp = await tmpdir({
  819. init: async (dir) => {
  820. const opencodeDir = path.join(dir, ".opencode")
  821. await fs.mkdir(opencodeDir, { recursive: true })
  822. const commandsDir = path.join(opencodeDir, "commands")
  823. await fs.mkdir(path.join(commandsDir, "nested"), { recursive: true })
  824. await Filesystem.write(
  825. path.join(commandsDir, "hello.md"),
  826. `---
  827. description: Test command
  828. ---
  829. Hello from plural commands`,
  830. )
  831. await Filesystem.write(
  832. path.join(commandsDir, "nested", "child.md"),
  833. `---
  834. description: Nested command
  835. ---
  836. Nested command template`,
  837. )
  838. },
  839. })
  840. await WithInstance.provide({
  841. directory: tmp.path,
  842. fn: async () => {
  843. const config = await load()
  844. expect(config.command?.["hello"]).toEqual({
  845. description: "Test command",
  846. template: "Hello from plural commands",
  847. })
  848. expect(config.command?.["nested/child"]).toEqual({
  849. description: "Nested command",
  850. template: "Nested command template",
  851. })
  852. },
  853. })
  854. })
  855. test("updates config and writes to file", async () => {
  856. await using tmp = await tmpdir()
  857. await WithInstance.provide({
  858. directory: tmp.path,
  859. fn: async () => {
  860. const newConfig = { model: "updated/model" }
  861. await save(newConfig as any)
  862. const writtenConfig = await Filesystem.readJson<{ model: string }>(path.join(tmp.path, "config.json"))
  863. expect(writtenConfig.model).toBe("updated/model")
  864. },
  865. })
  866. })
  867. test("gets config directories", async () => {
  868. await using tmp = await tmpdir()
  869. await WithInstance.provide({
  870. directory: tmp.path,
  871. fn: async () => {
  872. const dirs = await listDirs()
  873. expect(dirs.length).toBeGreaterThanOrEqual(1)
  874. },
  875. })
  876. })
  877. test("does not try to install dependencies in read-only OPENCODE_CONFIG_DIR", async () => {
  878. if (process.platform === "win32") return
  879. await using tmp = await tmpdir<string>({
  880. init: async (dir) => {
  881. const ro = path.join(dir, "readonly")
  882. await fs.mkdir(ro, { recursive: true })
  883. await fs.chmod(ro, 0o555)
  884. return ro
  885. },
  886. dispose: async (dir) => {
  887. const ro = path.join(dir, "readonly")
  888. await fs.chmod(ro, 0o755).catch(() => {})
  889. return ro
  890. },
  891. })
  892. const prev = process.env.OPENCODE_CONFIG_DIR
  893. process.env.OPENCODE_CONFIG_DIR = tmp.extra
  894. try {
  895. await WithInstance.provide({
  896. directory: tmp.path,
  897. fn: async () => {
  898. await load()
  899. },
  900. })
  901. } finally {
  902. if (prev === undefined) delete process.env.OPENCODE_CONFIG_DIR
  903. else process.env.OPENCODE_CONFIG_DIR = prev
  904. }
  905. })
  906. test("installs dependencies in writable OPENCODE_CONFIG_DIR", async () => {
  907. await using tmp = await tmpdir<string>({
  908. init: async (dir) => {
  909. const cfg = path.join(dir, "configdir")
  910. await fs.mkdir(cfg, { recursive: true })
  911. return cfg
  912. },
  913. })
  914. const prev = process.env.OPENCODE_CONFIG_DIR
  915. process.env.OPENCODE_CONFIG_DIR = tmp.extra
  916. const testLayer = Config.layer.pipe(
  917. Layer.provide(testFlock),
  918. Layer.provide(AppFileSystem.defaultLayer),
  919. Layer.provide(Env.defaultLayer),
  920. Layer.provide(emptyAuth),
  921. Layer.provide(emptyAccount),
  922. Layer.provideMerge(infra),
  923. Layer.provide(noopNpm),
  924. )
  925. try {
  926. await WithInstance.provide({
  927. directory: tmp.path,
  928. fn: async () => {
  929. await Effect.runPromise(Config.Service.use((svc) => svc.get()).pipe(Effect.scoped, Effect.provide(testLayer)))
  930. await Effect.runPromise(
  931. Config.Service.use((svc) => svc.waitForDependencies()).pipe(Effect.scoped, Effect.provide(testLayer)),
  932. )
  933. },
  934. })
  935. // TODO: this is a hack to wait for backgruounded gitignore
  936. await new Promise((resolve) => setTimeout(resolve, 1000))
  937. expect(await Filesystem.exists(path.join(tmp.extra, ".gitignore"))).toBe(true)
  938. expect(await Filesystem.readText(path.join(tmp.extra, ".gitignore"))).toContain("package-lock.json")
  939. } finally {
  940. if (prev === undefined) delete process.env.OPENCODE_CONFIG_DIR
  941. else process.env.OPENCODE_CONFIG_DIR = prev
  942. }
  943. })
  944. // Note: deduplication and serialization of npm installs is now handled by the
  945. // core Npm.Service (via EffectFlock). Those behaviors are tested in the core
  946. // package's npm tests, not here.
  947. test("resolves scoped npm plugins in config", async () => {
  948. await using tmp = await tmpdir({
  949. init: async (dir) => {
  950. const pluginDir = path.join(dir, "node_modules", "@scope", "plugin")
  951. await fs.mkdir(pluginDir, { recursive: true })
  952. await Filesystem.write(
  953. path.join(dir, "package.json"),
  954. JSON.stringify({ name: "config-fixture", version: "1.0.0", type: "module" }, null, 2),
  955. )
  956. await Filesystem.write(
  957. path.join(pluginDir, "package.json"),
  958. JSON.stringify(
  959. {
  960. name: "@scope/plugin",
  961. version: "1.0.0",
  962. type: "module",
  963. main: "./index.js",
  964. },
  965. null,
  966. 2,
  967. ),
  968. )
  969. await Filesystem.write(path.join(pluginDir, "index.js"), "export default {}\n")
  970. await Filesystem.write(
  971. path.join(dir, "opencode.json"),
  972. JSON.stringify({ $schema: "https://opencode.ai/config.json", plugin: ["@scope/plugin"] }, null, 2),
  973. )
  974. },
  975. })
  976. await provideTestInstance({
  977. directory: tmp.path,
  978. fn: async () => {
  979. const config = await load()
  980. const pluginEntries = config.plugin ?? []
  981. expect(pluginEntries).toContain("@scope/plugin")
  982. },
  983. })
  984. })
  985. test("merges plugin arrays from global and local configs", async () => {
  986. await using tmp = await tmpdir({
  987. init: async (dir) => {
  988. // Create a nested project structure with local .opencode config
  989. const projectDir = path.join(dir, "project")
  990. const opencodeDir = path.join(projectDir, ".opencode")
  991. await fs.mkdir(opencodeDir, { recursive: true })
  992. // Global config with plugins
  993. await Filesystem.write(
  994. path.join(dir, "opencode.json"),
  995. JSON.stringify({
  996. $schema: "https://opencode.ai/config.json",
  997. plugin: ["global-plugin-1", "global-plugin-2"],
  998. }),
  999. )
  1000. // Local .opencode config with different plugins
  1001. await Filesystem.write(
  1002. path.join(opencodeDir, "opencode.json"),
  1003. JSON.stringify({
  1004. $schema: "https://opencode.ai/config.json",
  1005. plugin: ["local-plugin-1"],
  1006. }),
  1007. )
  1008. },
  1009. })
  1010. await provideTestInstance({
  1011. directory: path.join(tmp.path, "project"),
  1012. fn: async () => {
  1013. const config = await load()
  1014. const plugins = config.plugin ?? []
  1015. // Should contain both global and local plugins
  1016. expect(plugins.some((p) => p.includes("global-plugin-1"))).toBe(true)
  1017. expect(plugins.some((p) => p.includes("global-plugin-2"))).toBe(true)
  1018. expect(plugins.some((p) => p.includes("local-plugin-1"))).toBe(true)
  1019. // Should have all 3 plugins (not replaced, but merged)
  1020. const pluginNames = plugins.filter((p) => p.includes("global-plugin") || p.includes("local-plugin"))
  1021. expect(pluginNames.length).toBeGreaterThanOrEqual(3)
  1022. },
  1023. })
  1024. })
  1025. test("does not error when only custom agent is a subagent", async () => {
  1026. await using tmp = await tmpdir({
  1027. init: async (dir) => {
  1028. const opencodeDir = path.join(dir, ".opencode")
  1029. await fs.mkdir(opencodeDir, { recursive: true })
  1030. const agentDir = path.join(opencodeDir, "agent")
  1031. await fs.mkdir(agentDir, { recursive: true })
  1032. await Filesystem.write(
  1033. path.join(agentDir, "helper.md"),
  1034. `---
  1035. model: test/model
  1036. mode: subagent
  1037. ---
  1038. Helper subagent prompt`,
  1039. )
  1040. },
  1041. })
  1042. await WithInstance.provide({
  1043. directory: tmp.path,
  1044. fn: async () => {
  1045. const config = await load()
  1046. expect(config.agent?.["helper"]).toMatchObject({
  1047. name: "helper",
  1048. model: "test/model",
  1049. mode: "subagent",
  1050. prompt: "Helper subagent prompt",
  1051. })
  1052. },
  1053. })
  1054. })
  1055. test("merges instructions arrays from global and local configs", async () => {
  1056. await using tmp = await tmpdir({
  1057. init: async (dir) => {
  1058. const projectDir = path.join(dir, "project")
  1059. const opencodeDir = path.join(projectDir, ".opencode")
  1060. await fs.mkdir(opencodeDir, { recursive: true })
  1061. await Filesystem.write(
  1062. path.join(dir, "opencode.json"),
  1063. JSON.stringify({
  1064. $schema: "https://opencode.ai/config.json",
  1065. instructions: ["global-instructions.md", "shared-rules.md"],
  1066. }),
  1067. )
  1068. await Filesystem.write(
  1069. path.join(opencodeDir, "opencode.json"),
  1070. JSON.stringify({
  1071. $schema: "https://opencode.ai/config.json",
  1072. instructions: ["local-instructions.md"],
  1073. }),
  1074. )
  1075. },
  1076. })
  1077. await WithInstance.provide({
  1078. directory: path.join(tmp.path, "project"),
  1079. fn: async () => {
  1080. const config = await load()
  1081. const instructions = config.instructions ?? []
  1082. expect(instructions).toContain("global-instructions.md")
  1083. expect(instructions).toContain("shared-rules.md")
  1084. expect(instructions).toContain("local-instructions.md")
  1085. expect(instructions.length).toBe(3)
  1086. },
  1087. })
  1088. })
  1089. test("deduplicates duplicate instructions from global and local configs", async () => {
  1090. await using tmp = await tmpdir({
  1091. init: async (dir) => {
  1092. const projectDir = path.join(dir, "project")
  1093. const opencodeDir = path.join(projectDir, ".opencode")
  1094. await fs.mkdir(opencodeDir, { recursive: true })
  1095. await Filesystem.write(
  1096. path.join(dir, "opencode.json"),
  1097. JSON.stringify({
  1098. $schema: "https://opencode.ai/config.json",
  1099. instructions: ["duplicate.md", "global-only.md"],
  1100. }),
  1101. )
  1102. await Filesystem.write(
  1103. path.join(opencodeDir, "opencode.json"),
  1104. JSON.stringify({
  1105. $schema: "https://opencode.ai/config.json",
  1106. instructions: ["duplicate.md", "local-only.md"],
  1107. }),
  1108. )
  1109. },
  1110. })
  1111. await WithInstance.provide({
  1112. directory: path.join(tmp.path, "project"),
  1113. fn: async () => {
  1114. const config = await load()
  1115. const instructions = config.instructions ?? []
  1116. expect(instructions).toContain("global-only.md")
  1117. expect(instructions).toContain("local-only.md")
  1118. expect(instructions).toContain("duplicate.md")
  1119. const duplicates = instructions.filter((i) => i === "duplicate.md")
  1120. expect(duplicates.length).toBe(1)
  1121. expect(instructions.length).toBe(3)
  1122. },
  1123. })
  1124. })
  1125. test("deduplicates duplicate plugins from global and local configs", async () => {
  1126. await using tmp = await tmpdir({
  1127. init: async (dir) => {
  1128. // Create a nested project structure with local .opencode config
  1129. const projectDir = path.join(dir, "project")
  1130. const opencodeDir = path.join(projectDir, ".opencode")
  1131. await fs.mkdir(opencodeDir, { recursive: true })
  1132. // Global config with plugins
  1133. await Filesystem.write(
  1134. path.join(dir, "opencode.json"),
  1135. JSON.stringify({
  1136. $schema: "https://opencode.ai/config.json",
  1137. plugin: ["duplicate-plugin", "global-plugin-1"],
  1138. }),
  1139. )
  1140. // Local .opencode config with some overlapping plugins
  1141. await Filesystem.write(
  1142. path.join(opencodeDir, "opencode.json"),
  1143. JSON.stringify({
  1144. $schema: "https://opencode.ai/config.json",
  1145. plugin: ["duplicate-plugin", "local-plugin-1"],
  1146. }),
  1147. )
  1148. },
  1149. })
  1150. await provideTestInstance({
  1151. directory: path.join(tmp.path, "project"),
  1152. fn: async () => {
  1153. const config = await load()
  1154. const plugins = config.plugin ?? []
  1155. // Should contain all unique plugins
  1156. expect(plugins.some((p) => p.includes("global-plugin-1"))).toBe(true)
  1157. expect(plugins.some((p) => p.includes("local-plugin-1"))).toBe(true)
  1158. expect(plugins.some((p) => p.includes("duplicate-plugin"))).toBe(true)
  1159. // Should deduplicate the duplicate plugin
  1160. const duplicatePlugins = plugins.filter((p) => p.includes("duplicate-plugin"))
  1161. expect(duplicatePlugins.length).toBe(1)
  1162. // Should have exactly 3 unique plugins
  1163. const pluginNames = plugins.filter(
  1164. (p) => p.includes("global-plugin") || p.includes("local-plugin") || p.includes("duplicate-plugin"),
  1165. )
  1166. expect(pluginNames.length).toBe(3)
  1167. },
  1168. })
  1169. })
  1170. test("keeps plugin origins aligned with merged plugin list", async () => {
  1171. await using tmp = await tmpdir({
  1172. init: async (dir) => {
  1173. const project = path.join(dir, "project")
  1174. const local = path.join(project, ".opencode")
  1175. await fs.mkdir(local, { recursive: true })
  1176. await Filesystem.write(
  1177. path.join(dir, "opencode.json"),
  1178. JSON.stringify({
  1179. $schema: "https://opencode.ai/config.json",
  1180. plugin: [["shared-plugin@1.0.0", { source: "global" }], "global-only@1.0.0"],
  1181. }),
  1182. )
  1183. await Filesystem.write(
  1184. path.join(local, "opencode.json"),
  1185. JSON.stringify({
  1186. $schema: "https://opencode.ai/config.json",
  1187. plugin: [["shared-plugin@2.0.0", { source: "local" }], "local-only@1.0.0"],
  1188. }),
  1189. )
  1190. },
  1191. })
  1192. await provideTestInstance({
  1193. directory: path.join(tmp.path, "project"),
  1194. fn: async () => {
  1195. const cfg = await load()
  1196. const plugins = cfg.plugin ?? []
  1197. const origins = cfg.plugin_origins ?? []
  1198. const names = plugins.map((item) => ConfigPlugin.pluginSpecifier(item))
  1199. expect(names).toContain("shared-plugin@2.0.0")
  1200. expect(names).not.toContain("shared-plugin@1.0.0")
  1201. expect(names).toContain("global-only@1.0.0")
  1202. expect(names).toContain("local-only@1.0.0")
  1203. expect(origins.map((item) => item.spec)).toEqual(plugins)
  1204. const hit = origins.find((item) => ConfigPlugin.pluginSpecifier(item.spec) === "shared-plugin@2.0.0")
  1205. expect(hit?.scope).toBe("local")
  1206. },
  1207. })
  1208. })
  1209. // Legacy tools migration tests
  1210. test("migrates legacy tools config to permissions - allow", async () => {
  1211. await using tmp = await tmpdir({
  1212. init: async (dir) => {
  1213. await Filesystem.write(
  1214. path.join(dir, "opencode.json"),
  1215. JSON.stringify({
  1216. $schema: "https://opencode.ai/config.json",
  1217. agent: {
  1218. test: {
  1219. tools: {
  1220. bash: true,
  1221. read: true,
  1222. },
  1223. },
  1224. },
  1225. }),
  1226. )
  1227. },
  1228. })
  1229. await WithInstance.provide({
  1230. directory: tmp.path,
  1231. fn: async () => {
  1232. const config = await load()
  1233. expect(config.agent?.["test"]?.permission).toEqual({
  1234. bash: "allow",
  1235. read: "allow",
  1236. })
  1237. },
  1238. })
  1239. })
  1240. test("migrates legacy tools config to permissions - deny", async () => {
  1241. await using tmp = await tmpdir({
  1242. init: async (dir) => {
  1243. await Filesystem.write(
  1244. path.join(dir, "opencode.json"),
  1245. JSON.stringify({
  1246. $schema: "https://opencode.ai/config.json",
  1247. agent: {
  1248. test: {
  1249. tools: {
  1250. bash: false,
  1251. webfetch: false,
  1252. },
  1253. },
  1254. },
  1255. }),
  1256. )
  1257. },
  1258. })
  1259. await WithInstance.provide({
  1260. directory: tmp.path,
  1261. fn: async () => {
  1262. const config = await load()
  1263. expect(config.agent?.["test"]?.permission).toEqual({
  1264. bash: "deny",
  1265. webfetch: "deny",
  1266. })
  1267. },
  1268. })
  1269. })
  1270. test("migrates legacy write tool to edit permission", async () => {
  1271. await using tmp = await tmpdir({
  1272. init: async (dir) => {
  1273. await Filesystem.write(
  1274. path.join(dir, "opencode.json"),
  1275. JSON.stringify({
  1276. $schema: "https://opencode.ai/config.json",
  1277. agent: {
  1278. test: {
  1279. tools: {
  1280. write: true,
  1281. },
  1282. },
  1283. },
  1284. }),
  1285. )
  1286. },
  1287. })
  1288. await WithInstance.provide({
  1289. directory: tmp.path,
  1290. fn: async () => {
  1291. const config = await load()
  1292. expect(config.agent?.["test"]?.permission).toEqual({
  1293. edit: "allow",
  1294. })
  1295. },
  1296. })
  1297. })
  1298. // Managed settings tests
  1299. // Note: preload.ts sets OPENCODE_TEST_MANAGED_CONFIG which Global.Path.managedConfig uses
  1300. test("managed settings override user settings", async () => {
  1301. await using tmp = await tmpdir({
  1302. init: async (dir) => {
  1303. await writeConfig(dir, {
  1304. $schema: "https://opencode.ai/config.json",
  1305. model: "user/model",
  1306. share: "auto",
  1307. username: "testuser",
  1308. })
  1309. },
  1310. })
  1311. await writeManagedSettings({
  1312. $schema: "https://opencode.ai/config.json",
  1313. model: "managed/model",
  1314. share: "disabled",
  1315. })
  1316. await WithInstance.provide({
  1317. directory: tmp.path,
  1318. fn: async () => {
  1319. const config = await load()
  1320. expect(config.model).toBe("managed/model")
  1321. expect(config.share).toBe("disabled")
  1322. expect(config.username).toBe("testuser")
  1323. },
  1324. })
  1325. })
  1326. test("managed settings override project settings", async () => {
  1327. await using tmp = await tmpdir({
  1328. init: async (dir) => {
  1329. await writeConfig(dir, {
  1330. $schema: "https://opencode.ai/config.json",
  1331. autoupdate: true,
  1332. disabled_providers: [],
  1333. })
  1334. },
  1335. })
  1336. await writeManagedSettings({
  1337. $schema: "https://opencode.ai/config.json",
  1338. autoupdate: false,
  1339. disabled_providers: ["openai"],
  1340. })
  1341. await WithInstance.provide({
  1342. directory: tmp.path,
  1343. fn: async () => {
  1344. const config = await load()
  1345. expect(config.autoupdate).toBe(false)
  1346. expect(config.disabled_providers).toEqual(["openai"])
  1347. },
  1348. })
  1349. })
  1350. test("missing managed settings file is not an error", async () => {
  1351. await using tmp = await tmpdir({
  1352. init: async (dir) => {
  1353. await writeConfig(dir, {
  1354. $schema: "https://opencode.ai/config.json",
  1355. model: "user/model",
  1356. })
  1357. },
  1358. })
  1359. await WithInstance.provide({
  1360. directory: tmp.path,
  1361. fn: async () => {
  1362. const config = await load()
  1363. expect(config.model).toBe("user/model")
  1364. },
  1365. })
  1366. })
  1367. test("migrates legacy edit tool to edit permission", async () => {
  1368. await using tmp = await tmpdir({
  1369. init: async (dir) => {
  1370. await Filesystem.write(
  1371. path.join(dir, "opencode.json"),
  1372. JSON.stringify({
  1373. $schema: "https://opencode.ai/config.json",
  1374. agent: {
  1375. test: {
  1376. tools: {
  1377. edit: false,
  1378. },
  1379. },
  1380. },
  1381. }),
  1382. )
  1383. },
  1384. })
  1385. await WithInstance.provide({
  1386. directory: tmp.path,
  1387. fn: async () => {
  1388. const config = await load()
  1389. expect(config.agent?.["test"]?.permission).toEqual({
  1390. edit: "deny",
  1391. })
  1392. },
  1393. })
  1394. })
  1395. test("migrates legacy patch tool to edit permission", async () => {
  1396. await using tmp = await tmpdir({
  1397. init: async (dir) => {
  1398. await Filesystem.write(
  1399. path.join(dir, "opencode.json"),
  1400. JSON.stringify({
  1401. $schema: "https://opencode.ai/config.json",
  1402. agent: {
  1403. test: {
  1404. tools: {
  1405. patch: true,
  1406. },
  1407. },
  1408. },
  1409. }),
  1410. )
  1411. },
  1412. })
  1413. await WithInstance.provide({
  1414. directory: tmp.path,
  1415. fn: async () => {
  1416. const config = await load()
  1417. expect(config.agent?.["test"]?.permission).toEqual({
  1418. edit: "allow",
  1419. })
  1420. },
  1421. })
  1422. })
  1423. test("migrates mixed legacy tools config", async () => {
  1424. await using tmp = await tmpdir({
  1425. init: async (dir) => {
  1426. await Filesystem.write(
  1427. path.join(dir, "opencode.json"),
  1428. JSON.stringify({
  1429. $schema: "https://opencode.ai/config.json",
  1430. agent: {
  1431. test: {
  1432. tools: {
  1433. bash: true,
  1434. write: true,
  1435. read: false,
  1436. webfetch: true,
  1437. },
  1438. },
  1439. },
  1440. }),
  1441. )
  1442. },
  1443. })
  1444. await WithInstance.provide({
  1445. directory: tmp.path,
  1446. fn: async () => {
  1447. const config = await load()
  1448. expect(config.agent?.["test"]?.permission).toEqual({
  1449. bash: "allow",
  1450. edit: "allow",
  1451. read: "deny",
  1452. webfetch: "allow",
  1453. })
  1454. },
  1455. })
  1456. })
  1457. test("merges legacy tools with existing permission config", async () => {
  1458. await using tmp = await tmpdir({
  1459. init: async (dir) => {
  1460. await Filesystem.write(
  1461. path.join(dir, "opencode.json"),
  1462. JSON.stringify({
  1463. $schema: "https://opencode.ai/config.json",
  1464. agent: {
  1465. test: {
  1466. permission: {
  1467. glob: "allow",
  1468. },
  1469. tools: {
  1470. bash: true,
  1471. },
  1472. },
  1473. },
  1474. }),
  1475. )
  1476. },
  1477. })
  1478. await WithInstance.provide({
  1479. directory: tmp.path,
  1480. fn: async () => {
  1481. const config = await load()
  1482. expect(config.agent?.["test"]?.permission).toEqual({
  1483. glob: "allow",
  1484. bash: "allow",
  1485. })
  1486. },
  1487. })
  1488. })
  1489. test("permission config preserves user key order", async () => {
  1490. // Permission precedence follows the order users write in config, so parsing
  1491. // must not canonicalise known keys ahead of wildcard or custom keys.
  1492. await using tmp = await tmpdir({
  1493. init: async (dir) => {
  1494. await Filesystem.write(
  1495. path.join(dir, "opencode.json"),
  1496. JSON.stringify({
  1497. $schema: "https://opencode.ai/config.json",
  1498. permission: {
  1499. "*": "deny",
  1500. edit: "ask",
  1501. write: "ask",
  1502. external_directory: "ask",
  1503. read: "allow",
  1504. todowrite: "allow",
  1505. "thoughts_*": "allow",
  1506. "reasoning_model_*": "allow",
  1507. "tools_*": "allow",
  1508. "pr_comments_*": "allow",
  1509. },
  1510. }),
  1511. )
  1512. },
  1513. })
  1514. await WithInstance.provide({
  1515. directory: tmp.path,
  1516. fn: async () => {
  1517. const config = await load()
  1518. expect(Object.keys(config.permission!)).toEqual([
  1519. "*",
  1520. "edit",
  1521. "write",
  1522. "external_directory",
  1523. "read",
  1524. "todowrite",
  1525. "thoughts_*",
  1526. "reasoning_model_*",
  1527. "tools_*",
  1528. "pr_comments_*",
  1529. ])
  1530. },
  1531. })
  1532. })
  1533. test("Effect config parser preserves permission order while rejecting unknown top-level keys", () => {
  1534. const config = ConfigParse.effectSchema(
  1535. Config.Info,
  1536. {
  1537. permission: {
  1538. bash: "allow",
  1539. "*": "deny",
  1540. edit: "ask",
  1541. },
  1542. },
  1543. "test",
  1544. )
  1545. expect(Object.keys(config.permission!)).toEqual(["bash", "*", "edit"])
  1546. try {
  1547. ConfigParse.effectSchema(Config.Info, { invalid_field: true }, "test")
  1548. throw new Error("expected config parse to fail")
  1549. } catch (err) {
  1550. const error = err as { data?: { issues?: Array<{ code?: string; keys?: string[]; path?: string[] }> } }
  1551. expect(error.data?.issues?.[0]).toMatchObject({ code: "unrecognized_keys", keys: ["invalid_field"], path: [] })
  1552. }
  1553. })
  1554. // MCP config merging tests
  1555. test("project config can override MCP server enabled status", async () => {
  1556. await using tmp = await tmpdir({
  1557. init: async (dir) => {
  1558. // Simulates a base config (like from remote .well-known) with disabled MCP
  1559. await Filesystem.write(
  1560. path.join(dir, "opencode.json"),
  1561. JSON.stringify({
  1562. $schema: "https://opencode.ai/config.json",
  1563. mcp: {
  1564. jira: {
  1565. type: "remote",
  1566. url: "https://jira.example.com/mcp",
  1567. enabled: false,
  1568. },
  1569. wiki: {
  1570. type: "remote",
  1571. url: "https://wiki.example.com/mcp",
  1572. enabled: false,
  1573. },
  1574. },
  1575. }),
  1576. )
  1577. // Project config enables just jira
  1578. await Filesystem.write(
  1579. path.join(dir, "opencode.jsonc"),
  1580. JSON.stringify({
  1581. $schema: "https://opencode.ai/config.json",
  1582. mcp: {
  1583. jira: {
  1584. type: "remote",
  1585. url: "https://jira.example.com/mcp",
  1586. enabled: true,
  1587. },
  1588. },
  1589. }),
  1590. )
  1591. },
  1592. })
  1593. await WithInstance.provide({
  1594. directory: tmp.path,
  1595. fn: async () => {
  1596. const config = await load()
  1597. // jira should be enabled (overridden by project config)
  1598. expect(config.mcp?.jira).toEqual({
  1599. type: "remote",
  1600. url: "https://jira.example.com/mcp",
  1601. enabled: true,
  1602. })
  1603. // wiki should still be disabled (not overridden)
  1604. expect(config.mcp?.wiki).toEqual({
  1605. type: "remote",
  1606. url: "https://wiki.example.com/mcp",
  1607. enabled: false,
  1608. })
  1609. },
  1610. })
  1611. })
  1612. test("MCP config deep merges preserving base config properties", async () => {
  1613. await using tmp = await tmpdir({
  1614. init: async (dir) => {
  1615. // Base config with full MCP definition
  1616. await Filesystem.write(
  1617. path.join(dir, "opencode.json"),
  1618. JSON.stringify({
  1619. $schema: "https://opencode.ai/config.json",
  1620. mcp: {
  1621. myserver: {
  1622. type: "remote",
  1623. url: "https://myserver.example.com/mcp",
  1624. enabled: false,
  1625. headers: {
  1626. "X-Custom-Header": "value",
  1627. },
  1628. },
  1629. },
  1630. }),
  1631. )
  1632. // Override just enables it, should preserve other properties
  1633. await Filesystem.write(
  1634. path.join(dir, "opencode.jsonc"),
  1635. JSON.stringify({
  1636. $schema: "https://opencode.ai/config.json",
  1637. mcp: {
  1638. myserver: {
  1639. type: "remote",
  1640. url: "https://myserver.example.com/mcp",
  1641. enabled: true,
  1642. },
  1643. },
  1644. }),
  1645. )
  1646. },
  1647. })
  1648. await WithInstance.provide({
  1649. directory: tmp.path,
  1650. fn: async () => {
  1651. const config = await load()
  1652. expect(config.mcp?.myserver).toEqual({
  1653. type: "remote",
  1654. url: "https://myserver.example.com/mcp",
  1655. enabled: true,
  1656. headers: {
  1657. "X-Custom-Header": "value",
  1658. },
  1659. })
  1660. },
  1661. })
  1662. })
  1663. test("local .opencode config can override MCP from project config", async () => {
  1664. await using tmp = await tmpdir({
  1665. init: async (dir) => {
  1666. // Project config with disabled MCP
  1667. await Filesystem.write(
  1668. path.join(dir, "opencode.json"),
  1669. JSON.stringify({
  1670. $schema: "https://opencode.ai/config.json",
  1671. mcp: {
  1672. docs: {
  1673. type: "remote",
  1674. url: "https://docs.example.com/mcp",
  1675. enabled: false,
  1676. },
  1677. },
  1678. }),
  1679. )
  1680. // Local .opencode directory config enables it
  1681. const opencodeDir = path.join(dir, ".opencode")
  1682. await fs.mkdir(opencodeDir, { recursive: true })
  1683. await Filesystem.write(
  1684. path.join(opencodeDir, "opencode.json"),
  1685. JSON.stringify({
  1686. $schema: "https://opencode.ai/config.json",
  1687. mcp: {
  1688. docs: {
  1689. type: "remote",
  1690. url: "https://docs.example.com/mcp",
  1691. enabled: true,
  1692. },
  1693. },
  1694. }),
  1695. )
  1696. },
  1697. })
  1698. await WithInstance.provide({
  1699. directory: tmp.path,
  1700. fn: async () => {
  1701. const config = await load()
  1702. expect(config.mcp?.docs?.enabled).toBe(true)
  1703. },
  1704. })
  1705. })
  1706. test("project config overrides remote well-known config", async () => {
  1707. const originalFetch = globalThis.fetch
  1708. let fetchedUrl: string | undefined
  1709. globalThis.fetch = mock((url: string | URL | Request) => {
  1710. const urlStr = url instanceof Request ? url.url : url instanceof URL ? url.href : url
  1711. if (urlStr.includes(".well-known/opencode")) {
  1712. fetchedUrl = urlStr
  1713. return Promise.resolve(
  1714. new Response(
  1715. JSON.stringify({
  1716. config: {
  1717. mcp: { jira: { type: "remote", url: "https://jira.example.com/mcp", enabled: false } },
  1718. },
  1719. }),
  1720. { status: 200 },
  1721. ),
  1722. )
  1723. }
  1724. return originalFetch(url)
  1725. }) as unknown as typeof fetch
  1726. const fakeAuth = Layer.mock(Auth.Service)({
  1727. all: () =>
  1728. Effect.succeed({
  1729. "https://example.com": new Auth.WellKnown({ type: "wellknown", key: "TEST_TOKEN", token: "test-token" }),
  1730. }),
  1731. })
  1732. const layer = Config.layer.pipe(
  1733. Layer.provide(testFlock),
  1734. Layer.provide(AppFileSystem.defaultLayer),
  1735. Layer.provide(Env.defaultLayer),
  1736. Layer.provide(fakeAuth),
  1737. Layer.provide(emptyAccount),
  1738. Layer.provideMerge(infra),
  1739. Layer.provide(noopNpm),
  1740. )
  1741. try {
  1742. await provideTmpdirInstance(
  1743. () =>
  1744. Config.Service.use((svc) =>
  1745. Effect.gen(function* () {
  1746. const config = yield* svc.get()
  1747. expect(fetchedUrl).toBe("https://example.com/.well-known/opencode")
  1748. expect(config.mcp?.jira?.enabled).toBe(true)
  1749. }),
  1750. ),
  1751. {
  1752. git: true,
  1753. config: { mcp: { jira: { type: "remote", url: "https://jira.example.com/mcp", enabled: true } } },
  1754. },
  1755. ).pipe(Effect.scoped, Effect.provide(layer), Effect.runPromise)
  1756. } finally {
  1757. globalThis.fetch = originalFetch
  1758. }
  1759. })
  1760. test("wellknown URL with trailing slash is normalized", async () => {
  1761. const originalFetch = globalThis.fetch
  1762. let fetchedUrl: string | undefined
  1763. globalThis.fetch = mock((url: string | URL | Request) => {
  1764. const urlStr = url instanceof Request ? url.url : url instanceof URL ? url.href : url
  1765. if (urlStr.includes(".well-known/opencode")) {
  1766. fetchedUrl = urlStr
  1767. return Promise.resolve(
  1768. new Response(
  1769. JSON.stringify({
  1770. config: {
  1771. mcp: { slack: { type: "remote", url: "https://slack.example.com/mcp", enabled: true } },
  1772. },
  1773. }),
  1774. { status: 200 },
  1775. ),
  1776. )
  1777. }
  1778. return originalFetch(url)
  1779. }) as unknown as typeof fetch
  1780. const fakeAuth = Layer.mock(Auth.Service)({
  1781. all: () =>
  1782. Effect.succeed({
  1783. "https://example.com/": new Auth.WellKnown({ type: "wellknown", key: "TEST_TOKEN", token: "test-token" }),
  1784. }),
  1785. })
  1786. const layer = Config.layer.pipe(
  1787. Layer.provide(testFlock),
  1788. Layer.provide(AppFileSystem.defaultLayer),
  1789. Layer.provide(Env.defaultLayer),
  1790. Layer.provide(fakeAuth),
  1791. Layer.provide(emptyAccount),
  1792. Layer.provideMerge(infra),
  1793. Layer.provide(noopNpm),
  1794. )
  1795. try {
  1796. await provideTmpdirInstance(
  1797. () =>
  1798. Config.Service.use((svc) =>
  1799. Effect.gen(function* () {
  1800. yield* svc.get()
  1801. expect(fetchedUrl).toBe("https://example.com/.well-known/opencode")
  1802. }),
  1803. ),
  1804. { git: true },
  1805. ).pipe(Effect.scoped, Effect.provide(layer), Effect.runPromise)
  1806. } finally {
  1807. globalThis.fetch = originalFetch
  1808. }
  1809. })
  1810. test("wellknown remote_config supports templated env vars in headers", async () => {
  1811. const originalFetch = globalThis.fetch
  1812. const originalToken = process.env.TEST_TOKEN
  1813. let wellknownFetchedUrl: string | undefined
  1814. let remoteFetchedUrl: string | undefined
  1815. let remoteHeaders: HeadersInit | undefined
  1816. globalThis.fetch = mock((url: string | URL | Request, init?: RequestInit) => {
  1817. const urlStr = url instanceof Request ? url.url : url instanceof URL ? url.href : url
  1818. if (urlStr.includes(".well-known/opencode")) {
  1819. wellknownFetchedUrl = urlStr
  1820. return Promise.resolve(
  1821. new Response(
  1822. JSON.stringify({
  1823. remote_config: {
  1824. url: "https://config.example.com/opencode.json",
  1825. headers: {
  1826. Authorization: "Bearer {env:TEST_TOKEN}",
  1827. },
  1828. },
  1829. }),
  1830. { status: 200 },
  1831. ),
  1832. )
  1833. }
  1834. if (urlStr.includes("config.example.com")) {
  1835. remoteFetchedUrl = urlStr
  1836. remoteHeaders = init?.headers
  1837. return Promise.resolve(
  1838. new Response(
  1839. JSON.stringify({
  1840. mcp: { confluence: { type: "remote", url: "https://confluence.example.com/mcp", enabled: true } },
  1841. }),
  1842. { status: 200 },
  1843. ),
  1844. )
  1845. }
  1846. return originalFetch(url, init)
  1847. }) as unknown as typeof fetch
  1848. const fakeAuth = Layer.mock(Auth.Service)({
  1849. all: () =>
  1850. Effect.succeed({
  1851. "https://example.com": new Auth.WellKnown({ type: "wellknown", key: "TEST_TOKEN", token: "test-token" }),
  1852. }),
  1853. })
  1854. const layer = Config.layer.pipe(
  1855. Layer.provide(testFlock),
  1856. Layer.provide(AppFileSystem.defaultLayer),
  1857. Layer.provide(Env.defaultLayer),
  1858. Layer.provide(fakeAuth),
  1859. Layer.provide(emptyAccount),
  1860. Layer.provideMerge(infra),
  1861. Layer.provide(noopNpm),
  1862. )
  1863. try {
  1864. await provideTmpdirInstance(
  1865. () =>
  1866. Config.Service.use((svc) =>
  1867. Effect.gen(function* () {
  1868. const config = yield* svc.get()
  1869. expect(wellknownFetchedUrl).toBe("https://example.com/.well-known/opencode")
  1870. expect(remoteFetchedUrl).toBe("https://config.example.com/opencode.json")
  1871. expect(remoteHeaders).toEqual({ Authorization: "Bearer test-token" })
  1872. expect(config.mcp?.confluence?.enabled).toBe(true)
  1873. }),
  1874. ),
  1875. { git: true },
  1876. ).pipe(Effect.scoped, Effect.provide(layer), Effect.runPromise)
  1877. } finally {
  1878. globalThis.fetch = originalFetch
  1879. if (originalToken === undefined) delete process.env.TEST_TOKEN
  1880. else process.env.TEST_TOKEN = originalToken
  1881. }
  1882. })
  1883. describe("resolvePluginSpec", () => {
  1884. test("keeps package specs unchanged", async () => {
  1885. await using tmp = await tmpdir()
  1886. const file = path.join(tmp.path, "opencode.json")
  1887. expect(await ConfigPlugin.resolvePluginSpec("oh-my-opencode@2.4.3", file)).toBe("oh-my-opencode@2.4.3")
  1888. expect(await ConfigPlugin.resolvePluginSpec("@scope/pkg", file)).toBe("@scope/pkg")
  1889. })
  1890. test("resolves windows-style relative plugin directory specs", async () => {
  1891. if (process.platform !== "win32") return
  1892. await using tmp = await tmpdir({
  1893. init: async (dir) => {
  1894. const plugin = path.join(dir, "plugin")
  1895. await fs.mkdir(plugin, { recursive: true })
  1896. await Filesystem.write(path.join(plugin, "index.ts"), "export default {}")
  1897. },
  1898. })
  1899. const file = path.join(tmp.path, "opencode.json")
  1900. const hit = await ConfigPlugin.resolvePluginSpec(".\\plugin", file)
  1901. expect(ConfigPlugin.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin", "index.ts")).href)
  1902. })
  1903. test("resolves relative file plugin paths to file urls", async () => {
  1904. await using tmp = await tmpdir({
  1905. init: async (dir) => {
  1906. await Filesystem.write(path.join(dir, "plugin.ts"), "export default {}")
  1907. },
  1908. })
  1909. const file = path.join(tmp.path, "opencode.json")
  1910. const hit = await ConfigPlugin.resolvePluginSpec("./plugin.ts", file)
  1911. expect(ConfigPlugin.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin.ts")).href)
  1912. })
  1913. test("resolves plugin directory paths to directory urls", async () => {
  1914. await using tmp = await tmpdir({
  1915. init: async (dir) => {
  1916. const plugin = path.join(dir, "plugin")
  1917. await fs.mkdir(plugin, { recursive: true })
  1918. await Filesystem.writeJson(path.join(plugin, "package.json"), {
  1919. name: "demo-plugin",
  1920. type: "module",
  1921. main: "./index.ts",
  1922. })
  1923. await Filesystem.write(path.join(plugin, "index.ts"), "export default {}")
  1924. },
  1925. })
  1926. const file = path.join(tmp.path, "opencode.json")
  1927. const hit = await ConfigPlugin.resolvePluginSpec("./plugin", file)
  1928. expect(ConfigPlugin.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin")).href)
  1929. })
  1930. test("resolves plugin directories without package.json to index.ts", async () => {
  1931. await using tmp = await tmpdir({
  1932. init: async (dir) => {
  1933. const plugin = path.join(dir, "plugin")
  1934. await fs.mkdir(plugin, { recursive: true })
  1935. await Filesystem.write(path.join(plugin, "index.ts"), "export default {}")
  1936. },
  1937. })
  1938. const file = path.join(tmp.path, "opencode.json")
  1939. const hit = await ConfigPlugin.resolvePluginSpec("./plugin", file)
  1940. expect(ConfigPlugin.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin", "index.ts")).href)
  1941. })
  1942. })
  1943. describe("deduplicatePluginOrigins", () => {
  1944. const dedupe = (plugins: ConfigPlugin.Spec[]) =>
  1945. ConfigPlugin.deduplicatePluginOrigins(
  1946. plugins.map((spec) => ({
  1947. spec,
  1948. source: "",
  1949. scope: "global" as const,
  1950. })),
  1951. ).map((item) => item.spec)
  1952. test("removes duplicates keeping higher priority (later entries)", () => {
  1953. const plugins = ["global-plugin@1.0.0", "shared-plugin@1.0.0", "local-plugin@2.0.0", "shared-plugin@2.0.0"]
  1954. const result = dedupe(plugins)
  1955. expect(result).toContain("global-plugin@1.0.0")
  1956. expect(result).toContain("local-plugin@2.0.0")
  1957. expect(result).toContain("shared-plugin@2.0.0")
  1958. expect(result).not.toContain("shared-plugin@1.0.0")
  1959. expect(result.length).toBe(3)
  1960. })
  1961. test("keeps path plugins separate from package plugins", () => {
  1962. const plugins = ["oh-my-opencode@2.4.3", "file:///project/.opencode/plugin/oh-my-opencode.js"]
  1963. const result = dedupe(plugins)
  1964. expect(result).toEqual(plugins)
  1965. })
  1966. test("deduplicates direct path plugins by exact spec", () => {
  1967. const plugins = ["file:///project/.opencode/plugin/demo.ts", "file:///project/.opencode/plugin/demo.ts"]
  1968. const result = dedupe(plugins)
  1969. expect(result).toEqual(["file:///project/.opencode/plugin/demo.ts"])
  1970. })
  1971. test("preserves order of remaining plugins", () => {
  1972. const plugins = ["a-plugin@1.0.0", "b-plugin@1.0.0", "c-plugin@1.0.0"]
  1973. const result = dedupe(plugins)
  1974. expect(result).toEqual(["a-plugin@1.0.0", "b-plugin@1.0.0", "c-plugin@1.0.0"])
  1975. })
  1976. test("loads auto-discovered local plugins as file urls", async () => {
  1977. await using tmp = await tmpdir({
  1978. init: async (dir) => {
  1979. const projectDir = path.join(dir, "project")
  1980. const opencodeDir = path.join(projectDir, ".opencode")
  1981. const pluginDir = path.join(opencodeDir, "plugin")
  1982. await fs.mkdir(pluginDir, { recursive: true })
  1983. await Filesystem.write(
  1984. path.join(dir, "opencode.json"),
  1985. JSON.stringify({
  1986. $schema: "https://opencode.ai/config.json",
  1987. plugin: ["my-plugin@1.0.0"],
  1988. }),
  1989. )
  1990. await Filesystem.write(path.join(pluginDir, "my-plugin.js"), "export default {}")
  1991. },
  1992. })
  1993. await provideTestInstance({
  1994. directory: path.join(tmp.path, "project"),
  1995. fn: async () => {
  1996. const config = await load()
  1997. const plugins = config.plugin ?? []
  1998. expect(plugins.some((p) => ConfigPlugin.pluginSpecifier(p) === "my-plugin@1.0.0")).toBe(true)
  1999. expect(plugins.some((p) => ConfigPlugin.pluginSpecifier(p).startsWith("file://"))).toBe(true)
  2000. },
  2001. })
  2002. })
  2003. })
  2004. describe("OPENCODE_DISABLE_PROJECT_CONFIG", () => {
  2005. test("skips project config files when flag is set", async () => {
  2006. const originalEnv = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  2007. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  2008. try {
  2009. await using tmp = await tmpdir({
  2010. init: async (dir) => {
  2011. // Create a project config that would normally be loaded
  2012. await Filesystem.write(
  2013. path.join(dir, "opencode.json"),
  2014. JSON.stringify({
  2015. $schema: "https://opencode.ai/config.json",
  2016. model: "project/model",
  2017. username: "project-user",
  2018. }),
  2019. )
  2020. },
  2021. })
  2022. await WithInstance.provide({
  2023. directory: tmp.path,
  2024. fn: async () => {
  2025. const config = await load()
  2026. // Project config should NOT be loaded - model should be default, not "project/model"
  2027. expect(config.model).not.toBe("project/model")
  2028. expect(config.username).not.toBe("project-user")
  2029. },
  2030. })
  2031. } finally {
  2032. if (originalEnv === undefined) {
  2033. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  2034. } else {
  2035. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalEnv
  2036. }
  2037. }
  2038. })
  2039. test("skips project .opencode/ directories when flag is set", async () => {
  2040. const originalEnv = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  2041. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  2042. try {
  2043. await using tmp = await tmpdir({
  2044. init: async (dir) => {
  2045. // Create a .opencode directory with a command
  2046. const opencodeDir = path.join(dir, ".opencode", "command")
  2047. await fs.mkdir(opencodeDir, { recursive: true })
  2048. await Filesystem.write(path.join(opencodeDir, "test-cmd.md"), "# Test Command\nThis is a test command.")
  2049. },
  2050. })
  2051. await WithInstance.provide({
  2052. directory: tmp.path,
  2053. fn: async () => {
  2054. const directories = await listDirs()
  2055. // Project .opencode should NOT be in directories list
  2056. const hasProjectOpencode = directories.some((d) => d.startsWith(tmp.path))
  2057. expect(hasProjectOpencode).toBe(false)
  2058. },
  2059. })
  2060. } finally {
  2061. if (originalEnv === undefined) {
  2062. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  2063. } else {
  2064. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalEnv
  2065. }
  2066. }
  2067. })
  2068. test("still loads global config when flag is set", async () => {
  2069. const originalEnv = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  2070. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  2071. try {
  2072. await using tmp = await tmpdir()
  2073. await WithInstance.provide({
  2074. directory: tmp.path,
  2075. fn: async () => {
  2076. // Should still get default config (from global or defaults)
  2077. const config = await load()
  2078. expect(config).toBeDefined()
  2079. expect(config.username).toBeDefined()
  2080. },
  2081. })
  2082. } finally {
  2083. if (originalEnv === undefined) {
  2084. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  2085. } else {
  2086. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalEnv
  2087. }
  2088. }
  2089. })
  2090. test("skips relative instructions with warning when flag is set but no config dir", async () => {
  2091. const originalDisable = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  2092. const originalConfigDir = process.env["OPENCODE_CONFIG_DIR"]
  2093. try {
  2094. // Ensure no config dir is set
  2095. delete process.env["OPENCODE_CONFIG_DIR"]
  2096. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  2097. await using tmp = await tmpdir({
  2098. init: async (dir) => {
  2099. // Create a config with relative instruction path
  2100. await Filesystem.write(
  2101. path.join(dir, "opencode.json"),
  2102. JSON.stringify({
  2103. $schema: "https://opencode.ai/config.json",
  2104. instructions: ["./CUSTOM.md"],
  2105. }),
  2106. )
  2107. // Create the instruction file (should be skipped)
  2108. await Filesystem.write(path.join(dir, "CUSTOM.md"), "# Custom Instructions")
  2109. },
  2110. })
  2111. await WithInstance.provide({
  2112. directory: tmp.path,
  2113. fn: async () => {
  2114. // The relative instruction should be skipped without error
  2115. // We're mainly verifying this doesn't throw and the config loads
  2116. const config = await load()
  2117. expect(config).toBeDefined()
  2118. // The instruction should have been skipped (warning logged)
  2119. // We can't easily test the warning was logged, but we verify
  2120. // the relative path didn't cause an error
  2121. },
  2122. })
  2123. } finally {
  2124. if (originalDisable === undefined) {
  2125. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  2126. } else {
  2127. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalDisable
  2128. }
  2129. if (originalConfigDir === undefined) {
  2130. delete process.env["OPENCODE_CONFIG_DIR"]
  2131. } else {
  2132. process.env["OPENCODE_CONFIG_DIR"] = originalConfigDir
  2133. }
  2134. }
  2135. })
  2136. test("OPENCODE_CONFIG_DIR still works when flag is set", async () => {
  2137. const originalDisable = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  2138. const originalConfigDir = process.env["OPENCODE_CONFIG_DIR"]
  2139. try {
  2140. await using configDirTmp = await tmpdir({
  2141. init: async (dir) => {
  2142. // Create config in the custom config dir
  2143. await Filesystem.write(
  2144. path.join(dir, "opencode.json"),
  2145. JSON.stringify({
  2146. $schema: "https://opencode.ai/config.json",
  2147. model: "configdir/model",
  2148. }),
  2149. )
  2150. },
  2151. })
  2152. await using projectTmp = await tmpdir({
  2153. init: async (dir) => {
  2154. // Create config in project (should be ignored)
  2155. await Filesystem.write(
  2156. path.join(dir, "opencode.json"),
  2157. JSON.stringify({
  2158. $schema: "https://opencode.ai/config.json",
  2159. model: "project/model",
  2160. }),
  2161. )
  2162. },
  2163. })
  2164. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  2165. process.env["OPENCODE_CONFIG_DIR"] = configDirTmp.path
  2166. await WithInstance.provide({
  2167. directory: projectTmp.path,
  2168. fn: async () => {
  2169. const config = await load()
  2170. // Should load from OPENCODE_CONFIG_DIR, not project
  2171. expect(config.model).toBe("configdir/model")
  2172. },
  2173. })
  2174. } finally {
  2175. if (originalDisable === undefined) {
  2176. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  2177. } else {
  2178. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalDisable
  2179. }
  2180. if (originalConfigDir === undefined) {
  2181. delete process.env["OPENCODE_CONFIG_DIR"]
  2182. } else {
  2183. process.env["OPENCODE_CONFIG_DIR"] = originalConfigDir
  2184. }
  2185. }
  2186. })
  2187. })
  2188. describe("OPENCODE_CONFIG_CONTENT token substitution", () => {
  2189. test("substitutes {env:} tokens in OPENCODE_CONFIG_CONTENT", async () => {
  2190. const originalEnv = process.env["OPENCODE_CONFIG_CONTENT"]
  2191. const originalTestVar = process.env["TEST_CONFIG_VAR"]
  2192. process.env["TEST_CONFIG_VAR"] = "test_api_key_12345"
  2193. process.env["OPENCODE_CONFIG_CONTENT"] = JSON.stringify({
  2194. $schema: "https://opencode.ai/config.json",
  2195. username: "{env:TEST_CONFIG_VAR}",
  2196. })
  2197. try {
  2198. await using tmp = await tmpdir()
  2199. await WithInstance.provide({
  2200. directory: tmp.path,
  2201. fn: async () => {
  2202. const config = await load()
  2203. expect(config.username).toBe("test_api_key_12345")
  2204. },
  2205. })
  2206. } finally {
  2207. if (originalEnv !== undefined) {
  2208. process.env["OPENCODE_CONFIG_CONTENT"] = originalEnv
  2209. } else {
  2210. delete process.env["OPENCODE_CONFIG_CONTENT"]
  2211. }
  2212. if (originalTestVar !== undefined) {
  2213. process.env["TEST_CONFIG_VAR"] = originalTestVar
  2214. } else {
  2215. delete process.env["TEST_CONFIG_VAR"]
  2216. }
  2217. }
  2218. })
  2219. test("substitutes {file:} tokens in OPENCODE_CONFIG_CONTENT", async () => {
  2220. const originalEnv = process.env["OPENCODE_CONFIG_CONTENT"]
  2221. try {
  2222. await using tmp = await tmpdir({
  2223. init: async (dir) => {
  2224. await Filesystem.write(path.join(dir, "api_key.txt"), "secret_key_from_file")
  2225. process.env["OPENCODE_CONFIG_CONTENT"] = JSON.stringify({
  2226. $schema: "https://opencode.ai/config.json",
  2227. username: "{file:./api_key.txt}",
  2228. })
  2229. },
  2230. })
  2231. await WithInstance.provide({
  2232. directory: tmp.path,
  2233. fn: async () => {
  2234. const config = await load()
  2235. expect(config.username).toBe("secret_key_from_file")
  2236. },
  2237. })
  2238. } finally {
  2239. if (originalEnv !== undefined) {
  2240. process.env["OPENCODE_CONFIG_CONTENT"] = originalEnv
  2241. } else {
  2242. delete process.env["OPENCODE_CONFIG_CONTENT"]
  2243. }
  2244. }
  2245. })
  2246. })
  2247. // parseManagedPlist unit tests — pure function, no OS interaction
  2248. test("parseManagedPlist strips MDM metadata keys", async () => {
  2249. const config = ConfigParse.effectSchema(
  2250. Config.Info,
  2251. ConfigParse.jsonc(
  2252. await ConfigManaged.parseManagedPlist(
  2253. JSON.stringify({
  2254. PayloadDisplayName: "OpenCode Managed",
  2255. PayloadIdentifier: "ai.opencode.managed.test",
  2256. PayloadType: "ai.opencode.managed",
  2257. PayloadUUID: "AAAA-BBBB-CCCC",
  2258. PayloadVersion: 1,
  2259. _manualProfile: true,
  2260. share: "disabled",
  2261. model: "mdm/model",
  2262. }),
  2263. ),
  2264. "test:mobileconfig",
  2265. ),
  2266. "test:mobileconfig",
  2267. )
  2268. expect(config.share).toBe("disabled")
  2269. expect(config.model).toBe("mdm/model")
  2270. // MDM keys must not leak into the parsed config
  2271. expect((config as any).PayloadUUID).toBeUndefined()
  2272. expect((config as any).PayloadType).toBeUndefined()
  2273. expect((config as any)._manualProfile).toBeUndefined()
  2274. })
  2275. test("parseManagedPlist parses server settings", async () => {
  2276. const config = ConfigParse.effectSchema(
  2277. Config.Info,
  2278. ConfigParse.jsonc(
  2279. await ConfigManaged.parseManagedPlist(
  2280. JSON.stringify({
  2281. $schema: "https://opencode.ai/config.json",
  2282. server: { hostname: "127.0.0.1", mdns: false },
  2283. autoupdate: true,
  2284. }),
  2285. ),
  2286. "test:mobileconfig",
  2287. ),
  2288. "test:mobileconfig",
  2289. )
  2290. expect(config.server?.hostname).toBe("127.0.0.1")
  2291. expect(config.server?.mdns).toBe(false)
  2292. expect(config.autoupdate).toBe(true)
  2293. })
  2294. test("parseManagedPlist parses permission rules", async () => {
  2295. const config = ConfigParse.effectSchema(
  2296. Config.Info,
  2297. ConfigParse.jsonc(
  2298. await ConfigManaged.parseManagedPlist(
  2299. JSON.stringify({
  2300. $schema: "https://opencode.ai/config.json",
  2301. permission: {
  2302. "*": "ask",
  2303. bash: { "*": "ask", "rm -rf *": "deny", "curl *": "deny" },
  2304. grep: "allow",
  2305. glob: "allow",
  2306. webfetch: "ask",
  2307. "~/.ssh/*": "deny",
  2308. },
  2309. }),
  2310. ),
  2311. "test:mobileconfig",
  2312. ),
  2313. "test:mobileconfig",
  2314. )
  2315. expect(config.permission?.["*"]).toBe("ask")
  2316. expect(config.permission?.grep).toBe("allow")
  2317. expect(config.permission?.webfetch).toBe("ask")
  2318. expect(config.permission?.["~/.ssh/*"]).toBe("deny")
  2319. const bash = config.permission?.bash as Record<string, string>
  2320. expect(bash?.["rm -rf *"]).toBe("deny")
  2321. expect(bash?.["curl *"]).toBe("deny")
  2322. })
  2323. test("parseManagedPlist parses enabled_providers", async () => {
  2324. const config = ConfigParse.effectSchema(
  2325. Config.Info,
  2326. ConfigParse.jsonc(
  2327. await ConfigManaged.parseManagedPlist(
  2328. JSON.stringify({
  2329. $schema: "https://opencode.ai/config.json",
  2330. enabled_providers: ["anthropic", "google"],
  2331. }),
  2332. ),
  2333. "test:mobileconfig",
  2334. ),
  2335. "test:mobileconfig",
  2336. )
  2337. expect(config.enabled_providers).toEqual(["anthropic", "google"])
  2338. })
  2339. test("parseManagedPlist handles empty config", async () => {
  2340. const config = ConfigParse.effectSchema(
  2341. Config.Info,
  2342. ConfigParse.jsonc(
  2343. await ConfigManaged.parseManagedPlist(JSON.stringify({ $schema: "https://opencode.ai/config.json" })),
  2344. "test:mobileconfig",
  2345. ),
  2346. "test:mobileconfig",
  2347. )
  2348. expect(config.$schema).toBe("https://opencode.ai/config.json")
  2349. })