command.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import fs from "fs/promises"
  2. import path from "path"
  3. import { describe, expect } from "bun:test"
  4. import { Deferred, Effect, Fiber, Layer, Option, PubSub, Schema, Stream } from "effect"
  5. import { advance, drain } from "../lib/clock"
  6. import { Config as ConfigSchema } from "@opencode-ai/schema/config"
  7. import { Command } from "@opencode-ai/core/command"
  8. import { Agent } from "@opencode-ai/core/agent"
  9. import { Config } from "@opencode-ai/core/config"
  10. import { ConfigCommandPlugin } from "@opencode-ai/core/config/plugin/command"
  11. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  12. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  13. import { FSUtil } from "@opencode-ai/util/fs-util"
  14. import { Bus } from "@opencode-ai/core/bus"
  15. import { Credential } from "@opencode-ai/core/credential"
  16. import { WellKnown } from "@opencode-ai/core/wellknown"
  17. import { Global } from "@opencode-ai/util/global"
  18. import { Location } from "@opencode-ai/core/location"
  19. import { MCP } from "@opencode-ai/core/mcp/index"
  20. import { Model } from "@opencode-ai/core/model"
  21. import { Provider } from "@opencode-ai/core/provider"
  22. import { AbsolutePath } from "@opencode-ai/core/schema"
  23. import { Watcher } from "@opencode-ai/core/filesystem/watcher"
  24. import { emptyCredentialNode, emptyWellknownNode } from "../fixture/config-nodes"
  25. import { emptyConfigLayer, emptyMcpLayer, testLocationLayer } from "../fixture/mcp"
  26. import { location } from "../fixture/location"
  27. import { tmpdir } from "../fixture/tmpdir"
  28. import { testEffect } from "../lib/effect"
  29. import { host } from "../plugin/host"
  30. const it = testEffect(
  31. AppNodeBuilder.build(LayerNode.group([Command.node, Bus.node, FSUtil.node]), [
  32. [MCP.node, emptyMcpLayer],
  33. [Config.node, emptyConfigLayer],
  34. [Location.node, testLocationLayer],
  35. ]),
  36. )
  37. const decode = Schema.decodeUnknownSync(Config.Info)
  38. describe("ConfigCommandPlugin.Plugin", () => {
  39. it.live("loads inline and file-based commands in config order", () =>
  40. Effect.acquireRelease(
  41. Effect.promise(() => tmpdir()),
  42. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  43. ).pipe(
  44. Effect.flatMap((tmp) =>
  45. Effect.gen(function* () {
  46. yield* Effect.promise(async () => {
  47. await fs.mkdir(path.join(tmp.path, "commands", "nested"), { recursive: true })
  48. await fs.writeFile(
  49. path.join(tmp.path, "commands", "review.md"),
  50. `---
  51. description: File review
  52. agent: reviewer
  53. model: anthropic/claude#high
  54. subtask: true
  55. ---
  56. Review files`,
  57. )
  58. await fs.writeFile(path.join(tmp.path, "commands", "nested", "docs.md"), "Write docs")
  59. await fs.writeFile(path.join(tmp.path, "commands", "empty.md"), "")
  60. })
  61. const command = yield* Command.Service
  62. const bus = yield* Bus.Service
  63. const update = yield* bus.publish(ConfigSchema.Event.Updated, {})
  64. const updates = yield* PubSub.unbounded<typeof update>()
  65. yield* ConfigCommandPlugin.Plugin.effect(
  66. host({
  67. command: {
  68. list: () => Effect.die("unused command.list"),
  69. transform: command.transform,
  70. reload: command.reload,
  71. },
  72. event: { subscribe: () => Stream.fromPubSub(updates) },
  73. }),
  74. ).pipe(
  75. Effect.provide(
  76. Config.testLayer([
  77. new Config.Document({
  78. type: "document",
  79. info: decode({ commands: { review: { template: "Inline review" } } }),
  80. }),
  81. new Config.Directory({ type: "directory", path: AbsolutePath.make(tmp.path) }),
  82. ]),
  83. ),
  84. )
  85. expect(yield* command.list()).toEqual([
  86. Command.Info.make({
  87. name: "review",
  88. template: "Review files",
  89. description: "File review",
  90. agent: Agent.ID.make("reviewer"),
  91. model: {
  92. providerID: Provider.ID.make("anthropic"),
  93. id: Model.ID.make("claude"),
  94. variant: Model.VariantID.make("high"),
  95. },
  96. subtask: true,
  97. }),
  98. Command.Info.make({ name: "empty", template: "" }),
  99. Command.Info.make({ name: "nested/docs", template: "Write docs" }),
  100. ])
  101. yield* Effect.promise(() => fs.writeFile(path.join(tmp.path, "commands", "review.md"), "Review again"))
  102. yield* Effect.sleep("10 millis")
  103. yield* PubSub.publish(updates, update)
  104. for (let attempt = 0; attempt < 100; attempt++) {
  105. if ((yield* command.get("review"))?.template === "Review again") break
  106. yield* Effect.sleep("10 millis")
  107. }
  108. expect((yield* command.get("review"))?.template).toBe("Review again")
  109. }),
  110. ),
  111. ),
  112. )
  113. for (const testCase of sourceCases()) {
  114. it.effect(`rebuilds commands when a source file is ${testCase.name}`, () =>
  115. Effect.acquireRelease(
  116. Effect.promise(() => tmpdir()),
  117. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  118. ).pipe(
  119. Effect.flatMap((tmp) =>
  120. Effect.gen(function* () {
  121. const directory = path.join(tmp.path, "commands")
  122. yield* Effect.promise(() => fs.mkdir(directory, { recursive: true }))
  123. yield* testCase.prepare(directory)
  124. const command = yield* Command.Service
  125. const bus = yield* Bus.Service
  126. const configTest = yield* Config.Test
  127. yield* ConfigCommandPlugin.Plugin.effect(
  128. host({
  129. command: {
  130. list: () => Effect.die("unused command.list"),
  131. transform: command.transform,
  132. reload: command.reload,
  133. },
  134. }),
  135. )
  136. // Verify inside the subscription so the update event is a read barrier:
  137. // committed state must be visible at event delivery time.
  138. let received = 0
  139. const changed = yield* bus.subscribe(Command.Event.Updated).pipe(
  140. Stream.take(1),
  141. Stream.tap(() => Effect.sync(() => received++)),
  142. Stream.mapEffect(() => testCase.verify(command)),
  143. Stream.runDrain,
  144. Effect.forkScoped({ startImmediately: true }),
  145. )
  146. yield* Effect.yieldNow
  147. const updates = yield* testCase.mutate(directory)
  148. yield* Effect.forEach(updates, (update) => configTest.emitChange(update), { discard: true })
  149. yield* advance(() => received === 1)
  150. yield* Fiber.join(changed)
  151. }).pipe(Effect.provide(Config.testLayer([directoryEntry(tmp.path)]))),
  152. ),
  153. ),
  154. )
  155. }
  156. it.effect("coalesces updates inside the debounce window into one rebuild", () =>
  157. Effect.acquireRelease(
  158. Effect.promise(() => tmpdir()),
  159. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  160. ).pipe(
  161. Effect.flatMap((tmp) =>
  162. Effect.gen(function* () {
  163. const directory = path.join(tmp.path, "commands")
  164. yield* Effect.promise(() => fs.mkdir(directory, { recursive: true }))
  165. const command = yield* Command.Service
  166. const configTest = yield* Config.Test
  167. let reloads = 0
  168. yield* ConfigCommandPlugin.Plugin.effect(
  169. host({
  170. command: {
  171. list: () => Effect.die("unused command.list"),
  172. transform: command.transform,
  173. reload: () => command.reload().pipe(Effect.tap(() => Effect.sync(() => reloads++))),
  174. },
  175. }),
  176. )
  177. yield* Effect.promise(() => fs.writeFile(path.join(directory, "review.md"), "Review once"))
  178. yield* configTest.emitChange({ type: "create", path: path.join(directory, "review.md") })
  179. yield* configTest.emitChange({ type: "update", path: path.join(directory, "review.md") })
  180. yield* configTest.emitChange({ type: "update", path: path.join(directory, "review.md") })
  181. yield* advance(() => reloads >= 1)
  182. expect(reloads).toBe(1)
  183. yield* Effect.promise(() => fs.writeFile(path.join(directory, "review.md"), "Review twice"))
  184. yield* configTest.emitChange({ type: "update", path: path.join(directory, "review.md") })
  185. yield* advance(() => reloads >= 2)
  186. expect(reloads).toBe(2)
  187. expect((yield* command.get("review"))?.template).toBe("Review twice")
  188. }).pipe(Effect.provide(Config.testLayer([directoryEntry(tmp.path)]))),
  189. ),
  190. ),
  191. )
  192. it.effect("ignores updates outside command source directories", () =>
  193. Effect.acquireRelease(
  194. Effect.promise(() => tmpdir()),
  195. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  196. ).pipe(
  197. Effect.flatMap((tmp) =>
  198. Effect.gen(function* () {
  199. const directory = path.join(tmp.path, "commands")
  200. yield* Effect.promise(() => fs.mkdir(directory, { recursive: true }))
  201. const command = yield* Command.Service
  202. const configTest = yield* Config.Test
  203. let reloads = 0
  204. yield* ConfigCommandPlugin.Plugin.effect(
  205. host({
  206. command: {
  207. list: () => Effect.die("unused command.list"),
  208. transform: command.transform,
  209. reload: () => command.reload().pipe(Effect.tap(() => Effect.sync(() => reloads++))),
  210. },
  211. }),
  212. )
  213. yield* configTest.emitChange({ type: "create", path: path.join(tmp.path, "notes", "todo.md") })
  214. yield* configTest.emitChange({ type: "update", path: path.join(tmp.path, "opencode.json") })
  215. yield* drain
  216. expect(reloads).toBe(0)
  217. // The feed stays live after unrelated updates.
  218. yield* Effect.promise(() => fs.writeFile(path.join(directory, "review.md"), "Review related"))
  219. yield* configTest.emitChange({ type: "create", path: path.join(directory, "review.md") })
  220. yield* advance(() => reloads >= 1)
  221. expect((yield* command.get("review"))?.template).toBe("Review related")
  222. }).pipe(Effect.provide(Config.testLayer([directoryEntry(tmp.path)]))),
  223. ),
  224. ),
  225. )
  226. })
  227. const describeNative = Watcher.hasNativeBinding() && !process.env.CI ? describe : describe.skip
  228. // End-to-end proof for #37429: a real file edit reaches the command registry
  229. // through the native watcher, Config's watch topology, the source filter, and
  230. // the debounced reload — no mocked change feed.
  231. describeNative("ConfigCommandPlugin native watcher", () => {
  232. it.live("reloads commands from real file edits", () =>
  233. Effect.gen(function* () {
  234. const fs = yield* FSUtil.Service
  235. // Watcher events report real paths, so resolve the tempdir symlink up front.
  236. const tmp = yield* fs.makeTempDirectoryScoped({ prefix: "opencode-core-test-" }).pipe(Effect.flatMap(fs.realPath))
  237. const global = path.join(tmp, "global")
  238. yield* fs.makeDirectory(path.join(global, "commands"), { recursive: true })
  239. yield* fs.makeDirectory(path.join(tmp, "project"))
  240. yield* Effect.gen(function* () {
  241. const command = yield* Command.Service
  242. const config = yield* Config.Service
  243. const bus = yield* Bus.Service
  244. yield* ConfigCommandPlugin.Plugin.effect(
  245. host({
  246. command: {
  247. list: () => Effect.die("unused command.list"),
  248. transform: command.transform,
  249. reload: command.reload,
  250. },
  251. }),
  252. )
  253. yield* watchReady(config, global)
  254. const created = yield* nextCommandUpdate(bus)
  255. yield* fs.writeFileString(path.join(global, "commands", "review.md"), "Review native")
  256. yield* Fiber.join(created).pipe(Effect.timeout("10 seconds"))
  257. expect((yield* command.get("review"))?.template).toBe("Review native")
  258. const updated = yield* nextCommandUpdate(bus)
  259. yield* fs.writeFileString(path.join(global, "commands", "review.md"), "Review native again")
  260. yield* Fiber.join(updated).pipe(Effect.timeout("10 seconds"))
  261. expect((yield* command.get("review"))?.template).toBe("Review native again")
  262. }).pipe(
  263. Effect.provide(
  264. AppNodeBuilder.build(LayerNode.group([Command.node, Config.node, Bus.node, FSUtil.node]), [
  265. [
  266. Location.node,
  267. Layer.succeed(
  268. Location.Service,
  269. Location.Service.of(location({ directory: AbsolutePath.make(path.join(tmp, "project")) })),
  270. ),
  271. ],
  272. [Global.node, Global.layerWith({ config: global, home: path.join(global, "home") })],
  273. [Credential.node, emptyCredentialNode],
  274. [WellKnown.node, emptyWellknownNode],
  275. ]),
  276. ),
  277. )
  278. }),
  279. )
  280. })
  281. function nextCommandUpdate(bus: Bus.Interface) {
  282. return bus
  283. .subscribe(Command.Event.Updated)
  284. .pipe(Stream.take(1), Stream.runDrain, Effect.forkScoped({ startImmediately: true }))
  285. }
  286. // Native directory watches start asynchronously; probe with unrelated files
  287. // until the change feed delivers so command edits afterwards cannot be missed.
  288. function watchReady(config: Config.Interface, directory: string) {
  289. return Effect.gen(function* () {
  290. const fs = yield* FSUtil.Service
  291. const seen = yield* Deferred.make<void>()
  292. const listener = yield* config.changes().pipe(
  293. Stream.runForEach(() => Deferred.succeed(seen, undefined).pipe(Effect.asVoid)),
  294. Effect.forkScoped({ startImmediately: true }),
  295. )
  296. yield* Effect.yieldNow
  297. const probe = path.join(directory, ".watch-probe")
  298. while (true) {
  299. yield* fs.writeFileString(probe, `ready-${Math.random()}`)
  300. const result = yield* Deferred.await(seen).pipe(Effect.timeoutOption("250 millis"))
  301. if (Option.isSome(result)) break
  302. }
  303. yield* Fiber.interrupt(listener)
  304. yield* fs.remove(probe, { force: true })
  305. }).pipe(
  306. Effect.timeoutOrElse({
  307. duration: "10 seconds",
  308. orElse: () => Effect.fail(new Error("timed out waiting for the config watch to become ready")),
  309. }),
  310. )
  311. }
  312. function directoryEntry(directory: string) {
  313. return new Config.Directory({ type: "directory", path: AbsolutePath.make(directory) })
  314. }
  315. function sourceCases() {
  316. return [
  317. {
  318. name: "created",
  319. prepare: () => Effect.void,
  320. mutate: (directory: string) =>
  321. Effect.promise(async () => {
  322. const file = path.join(directory, "review.md")
  323. await fs.writeFile(file, "Review created")
  324. return [{ type: "create" as const, path: file }]
  325. }),
  326. verify: (command: Command.Interface) =>
  327. Effect.gen(function* () {
  328. expect((yield* command.get("review"))?.template).toBe("Review created")
  329. }),
  330. },
  331. {
  332. name: "updated",
  333. prepare: (directory: string) =>
  334. Effect.promise(() => fs.writeFile(path.join(directory, "review.md"), "Review first")),
  335. mutate: (directory: string) =>
  336. Effect.promise(async () => {
  337. const file = path.join(directory, "review.md")
  338. await fs.writeFile(file, "Review updated")
  339. return [{ type: "update" as const, path: file }]
  340. }),
  341. verify: (command: Command.Interface) =>
  342. Effect.gen(function* () {
  343. expect((yield* command.get("review"))?.template).toBe("Review updated")
  344. }),
  345. },
  346. {
  347. name: "renamed",
  348. prepare: (directory: string) =>
  349. Effect.promise(() => fs.writeFile(path.join(directory, "review.md"), "Review renamed")),
  350. mutate: (directory: string) =>
  351. Effect.promise(async () => {
  352. const previous = path.join(directory, "review.md")
  353. const next = path.join(directory, "release.md")
  354. await fs.rename(previous, next)
  355. return [
  356. { type: "delete" as const, path: previous },
  357. { type: "create" as const, path: next },
  358. ]
  359. }),
  360. verify: (command: Command.Interface) =>
  361. Effect.gen(function* () {
  362. expect(yield* command.get("review")).toBeUndefined()
  363. expect((yield* command.get("release"))?.template).toBe("Review renamed")
  364. }),
  365. },
  366. {
  367. name: "deleted",
  368. prepare: (directory: string) =>
  369. Effect.promise(() => fs.writeFile(path.join(directory, "review.md"), "Review deleted")),
  370. mutate: (directory: string) =>
  371. Effect.promise(async () => {
  372. const file = path.join(directory, "review.md")
  373. await fs.unlink(file)
  374. return [{ type: "delete" as const, path: file }]
  375. }),
  376. verify: (command: Command.Interface) =>
  377. Effect.gen(function* () {
  378. expect(yield* command.get("review")).toBeUndefined()
  379. }),
  380. },
  381. ] as const
  382. }