command.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 { Directory, Document, Event, Info } 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(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(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 Document({
  78. type: "document",
  79. info: decode({ commands: { review: { template: "Inline review" } } }),
  80. }),
  81. new 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.yieldNow
  178. yield* Effect.promise(() => fs.writeFile(path.join(directory, "review.md"), "Review once"))
  179. yield* configTest.emitChange({ type: "create", path: path.join(directory, "review.md") })
  180. yield* configTest.emitChange({ type: "update", path: path.join(directory, "review.md") })
  181. yield* configTest.emitChange({ type: "update", path: path.join(directory, "review.md") })
  182. yield* advance(() => reloads >= 1)
  183. expect(reloads).toBe(1)
  184. yield* Effect.promise(() => fs.writeFile(path.join(directory, "review.md"), "Review twice"))
  185. yield* configTest.emitChange({ type: "update", path: path.join(directory, "review.md") })
  186. yield* advance(() => reloads >= 2)
  187. expect(reloads).toBe(2)
  188. expect((yield* command.get("review"))?.template).toBe("Review twice")
  189. }).pipe(Effect.provide(Config.testLayer([directoryEntry(tmp.path)]))),
  190. ),
  191. ),
  192. )
  193. it.effect("ignores updates outside command source directories", () =>
  194. Effect.acquireRelease(
  195. Effect.promise(() => tmpdir()),
  196. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  197. ).pipe(
  198. Effect.flatMap((tmp) =>
  199. Effect.gen(function* () {
  200. const directory = path.join(tmp.path, "commands")
  201. yield* Effect.promise(() => fs.mkdir(directory, { recursive: true }))
  202. const command = yield* Command.Service
  203. const configTest = yield* Config.Test
  204. let reloads = 0
  205. yield* ConfigCommandPlugin.Plugin.effect(
  206. host({
  207. command: {
  208. list: () => Effect.die("unused command.list"),
  209. transform: command.transform,
  210. reload: () => command.reload().pipe(Effect.tap(() => Effect.sync(() => reloads++))),
  211. },
  212. }),
  213. )
  214. yield* configTest.emitChange({ type: "create", path: path.join(tmp.path, "notes", "todo.md") })
  215. yield* configTest.emitChange({ type: "update", path: path.join(tmp.path, "opencode.json") })
  216. yield* drain
  217. expect(reloads).toBe(0)
  218. // The feed stays live after unrelated updates.
  219. yield* Effect.promise(() => fs.writeFile(path.join(directory, "review.md"), "Review related"))
  220. yield* configTest.emitChange({ type: "create", path: path.join(directory, "review.md") })
  221. yield* advance(() => reloads >= 1)
  222. expect((yield* command.get("review"))?.template).toBe("Review related")
  223. }).pipe(Effect.provide(Config.testLayer([directoryEntry(tmp.path)]))),
  224. ),
  225. ),
  226. )
  227. })
  228. const describeNative = Watcher.hasNativeBinding() && !process.env.CI ? describe : describe.skip
  229. // End-to-end proof for #37429: a real file edit reaches the command registry
  230. // through the native watcher, Config's watch topology, the source filter, and
  231. // the debounced reload — no mocked change feed.
  232. describeNative("ConfigCommandPlugin native watcher", () => {
  233. it.live("reloads commands from real file edits", () =>
  234. Effect.gen(function* () {
  235. const fs = yield* FSUtil.Service
  236. // Watcher events report real paths, so resolve the tempdir symlink up front.
  237. const tmp = yield* fs.makeTempDirectoryScoped({ prefix: "opencode-core-test-" }).pipe(Effect.flatMap(fs.realPath))
  238. const global = path.join(tmp, "global")
  239. yield* fs.makeDirectory(path.join(global, "commands"), { recursive: true })
  240. yield* fs.makeDirectory(path.join(tmp, "project"))
  241. yield* Effect.gen(function* () {
  242. const command = yield* Command.Service
  243. const config = yield* Config.Service
  244. const bus = yield* Bus.Service
  245. yield* ConfigCommandPlugin.Plugin.effect(
  246. host({
  247. command: {
  248. list: () => Effect.die("unused command.list"),
  249. transform: command.transform,
  250. reload: command.reload,
  251. },
  252. }),
  253. )
  254. yield* watchReady(config, global)
  255. const created = yield* nextCommandUpdate(bus)
  256. yield* fs.writeFileString(path.join(global, "commands", "review.md"), "Review native")
  257. yield* Fiber.join(created).pipe(Effect.timeout("10 seconds"))
  258. expect((yield* command.get("review"))?.template).toBe("Review native")
  259. const updated = yield* nextCommandUpdate(bus)
  260. yield* fs.writeFileString(path.join(global, "commands", "review.md"), "Review native again")
  261. yield* Fiber.join(updated).pipe(Effect.timeout("10 seconds"))
  262. expect((yield* command.get("review"))?.template).toBe("Review native again")
  263. }).pipe(
  264. Effect.provide(
  265. AppNodeBuilder.build(LayerNode.group([Command.node, Config.node, Bus.node, FSUtil.node]), [
  266. [
  267. Location.node,
  268. Layer.succeed(
  269. Location.Service,
  270. Location.Service.of(location({ directory: AbsolutePath.make(path.join(tmp, "project")) })),
  271. ),
  272. ],
  273. [Global.node, Global.layerWith({ config: global, home: path.join(global, "home") })],
  274. [Credential.node, emptyCredentialNode],
  275. [WellKnown.node, emptyWellknownNode],
  276. ]),
  277. ),
  278. )
  279. }),
  280. )
  281. })
  282. function nextCommandUpdate(bus: Bus.Interface) {
  283. return bus
  284. .subscribe(Command.Event.Updated)
  285. .pipe(Stream.take(1), Stream.runDrain, Effect.forkScoped({ startImmediately: true }))
  286. }
  287. // Native directory watches start asynchronously; probe with unrelated files
  288. // until the change feed delivers so command edits afterwards cannot be missed.
  289. function watchReady(config: Config.Interface, directory: string) {
  290. return Effect.gen(function* () {
  291. const fs = yield* FSUtil.Service
  292. const seen = yield* Deferred.make<void>()
  293. const listener = yield* config.changes().pipe(
  294. Stream.runForEach(() => Deferred.succeed(seen, undefined).pipe(Effect.asVoid)),
  295. Effect.forkScoped({ startImmediately: true }),
  296. )
  297. yield* Effect.yieldNow
  298. const probe = path.join(directory, ".watch-probe")
  299. while (true) {
  300. yield* fs.writeFileString(probe, `ready-${Math.random()}`)
  301. const result = yield* Deferred.await(seen).pipe(Effect.timeoutOption("250 millis"))
  302. if (Option.isSome(result)) break
  303. }
  304. yield* Fiber.interrupt(listener)
  305. yield* fs.remove(probe, { force: true })
  306. }).pipe(
  307. Effect.timeoutOrElse({
  308. duration: "10 seconds",
  309. orElse: () => Effect.fail(new Error("timed out waiting for the config watch to become ready")),
  310. }),
  311. )
  312. }
  313. function directoryEntry(directory: string) {
  314. return new Directory({ type: "directory", path: AbsolutePath.make(directory) })
  315. }
  316. function sourceCases() {
  317. return [
  318. {
  319. name: "created",
  320. prepare: () => Effect.void,
  321. mutate: (directory: string) =>
  322. Effect.promise(async () => {
  323. const file = path.join(directory, "review.md")
  324. await fs.writeFile(file, "Review created")
  325. return [{ type: "create" as const, path: file }]
  326. }),
  327. verify: (command: Command.Interface) =>
  328. Effect.gen(function* () {
  329. expect((yield* command.get("review"))?.template).toBe("Review created")
  330. }),
  331. },
  332. {
  333. name: "updated",
  334. prepare: (directory: string) =>
  335. Effect.promise(() => fs.writeFile(path.join(directory, "review.md"), "Review first")),
  336. mutate: (directory: string) =>
  337. Effect.promise(async () => {
  338. const file = path.join(directory, "review.md")
  339. await fs.writeFile(file, "Review updated")
  340. return [{ type: "update" as const, path: file }]
  341. }),
  342. verify: (command: Command.Interface) =>
  343. Effect.gen(function* () {
  344. expect((yield* command.get("review"))?.template).toBe("Review updated")
  345. }),
  346. },
  347. {
  348. name: "renamed",
  349. prepare: (directory: string) =>
  350. Effect.promise(() => fs.writeFile(path.join(directory, "review.md"), "Review renamed")),
  351. mutate: (directory: string) =>
  352. Effect.promise(async () => {
  353. const previous = path.join(directory, "review.md")
  354. const next = path.join(directory, "release.md")
  355. await fs.rename(previous, next)
  356. return [
  357. { type: "delete" as const, path: previous },
  358. { type: "create" as const, path: next },
  359. ]
  360. }),
  361. verify: (command: Command.Interface) =>
  362. Effect.gen(function* () {
  363. expect(yield* command.get("review")).toBeUndefined()
  364. expect((yield* command.get("release"))?.template).toBe("Review renamed")
  365. }),
  366. },
  367. {
  368. name: "deleted",
  369. prepare: (directory: string) =>
  370. Effect.promise(() => fs.writeFile(path.join(directory, "review.md"), "Review deleted")),
  371. mutate: (directory: string) =>
  372. Effect.promise(async () => {
  373. const file = path.join(directory, "review.md")
  374. await fs.unlink(file)
  375. return [{ type: "delete" as const, path: file }]
  376. }),
  377. verify: (command: Command.Interface) =>
  378. Effect.gen(function* () {
  379. expect(yield* command.get("review")).toBeUndefined()
  380. }),
  381. },
  382. ] as const
  383. }