tool-patch.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. import fs from "fs/promises"
  2. import path from "path"
  3. import { describe, expect } from "bun:test"
  4. import { Deferred, Effect, Exit, Fiber, Layer } from "effect"
  5. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  6. import { LayerNode } from "@opencode-ai/core/effect/layer-node"
  7. import { FileMutation } from "@opencode-ai/core/file-mutation"
  8. import { FSUtil } from "@opencode-ai/core/fs-util"
  9. import { Location } from "@opencode-ai/core/location"
  10. import { LocationMutation } from "@opencode-ai/core/location-mutation"
  11. import { PermissionV2 } from "@opencode-ai/core/permission"
  12. import { AbsolutePath } from "@opencode-ai/core/schema"
  13. import { SessionV2 } from "@opencode-ai/core/session"
  14. import { ToolRegistry } from "@opencode-ai/core/tool/registry"
  15. import { ToolOutputStore } from "@opencode-ai/core/tool-output-store"
  16. import { PatchTool } from "@opencode-ai/core/tool/patch"
  17. import { location } from "./fixture/location"
  18. import { tmpdir } from "./fixture/tmpdir"
  19. import { makeLocationNode } from "@opencode-ai/core/effect/app-node"
  20. import { testEffect } from "./lib/effect"
  21. import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool"
  22. const patchToolNode = makeLocationNode({
  23. name: "test/patch-tool-plugin",
  24. layer: Layer.effectDiscard(registerToolPlugin(PatchTool.Plugin)),
  25. deps: [ToolRegistry.toolsNode, LocationMutation.node, FileMutation.node, FSUtil.node, PermissionV2.node],
  26. })
  27. const sessionID = SessionV2.ID.make("ses_patch_tool_test")
  28. const assertions: PermissionV2.AssertInput[] = []
  29. let denyAction: string | undefined
  30. let failRemoveTarget: string | undefined
  31. let readsBeforeEditApproval = 0
  32. let editApproved = false
  33. let blockRemoveTarget: string | undefined
  34. let removeStarted: Deferred.Deferred<void> | undefined
  35. let releaseRemove: Deferred.Deferred<void> | undefined
  36. let afterEditApproval = (): Effect.Effect<void> => Effect.void
  37. const permission = Layer.succeed(
  38. PermissionV2.Service,
  39. PermissionV2.Service.of({
  40. assert: (input) =>
  41. Effect.sync(() => {
  42. assertions.push(input)
  43. if (input.action === "edit") editApproved = true
  44. }).pipe(
  45. Effect.andThen(input.action === "edit" ? Effect.suspend(afterEditApproval) : Effect.void),
  46. Effect.andThen(
  47. input.action === denyAction
  48. ? Effect.fail(
  49. new PermissionV2.BlockedError({
  50. rules: [],
  51. permission: input.action,
  52. resources: input.resources,
  53. }),
  54. )
  55. : Effect.void,
  56. ),
  57. ),
  58. ask: () => Effect.die("unused"),
  59. reply: () => Effect.die("unused"),
  60. get: () => Effect.die("unused"),
  61. forSession: () => Effect.die("unused"),
  62. list: () => Effect.die("unused"),
  63. }),
  64. )
  65. const reset = () => {
  66. assertions.length = 0
  67. denyAction = undefined
  68. failRemoveTarget = undefined
  69. readsBeforeEditApproval = 0
  70. editApproved = false
  71. blockRemoveTarget = undefined
  72. removeStarted = undefined
  73. releaseRemove = undefined
  74. afterEditApproval = () => Effect.void
  75. }
  76. const filesystem = Layer.effect(
  77. FSUtil.Service,
  78. Effect.gen(function* () {
  79. const fs = yield* FSUtil.Service
  80. return FSUtil.Service.of({
  81. ...fs,
  82. readFile: (target) =>
  83. Effect.sync(() => {
  84. if (!editApproved) readsBeforeEditApproval++
  85. }).pipe(Effect.andThen(fs.readFile(target))),
  86. remove: (target, options) => {
  87. if (failRemoveTarget && path.basename(target) === failRemoveTarget) return Effect.die("forced remove failure")
  88. if (blockRemoveTarget && path.basename(target) === blockRemoveTarget && removeStarted && releaseRemove)
  89. return Deferred.succeed(removeStarted, undefined).pipe(
  90. Effect.andThen(Deferred.await(releaseRemove)),
  91. Effect.andThen(fs.remove(target, options)),
  92. )
  93. return fs.remove(target, options)
  94. },
  95. })
  96. }),
  97. ).pipe(Layer.provide(LayerNode.compile(FSUtil.node)))
  98. const withTool = <A, E, R>(directory: string, body: (registry: ToolRegistry.Interface) => Effect.Effect<A, E, R>) => {
  99. const activeLocation = Layer.succeed(
  100. Location.Service,
  101. Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
  102. )
  103. return Effect.gen(function* () {
  104. return yield* body(yield* ToolRegistry.Service)
  105. }).pipe(
  106. Effect.provide(
  107. AppNodeBuilder.build(
  108. LayerNode.group([
  109. ToolRegistry.node,
  110. ToolRegistry.toolsNode,
  111. LocationMutation.node,
  112. FileMutation.node,
  113. patchToolNode,
  114. ]),
  115. [
  116. [FSUtil.node, filesystem],
  117. [Location.node, activeLocation],
  118. [PermissionV2.node, permission],
  119. [ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig],
  120. ],
  121. ),
  122. ),
  123. )
  124. }
  125. const call = (patchText: string, id = "call-patch") => ({
  126. sessionID,
  127. ...toolIdentity,
  128. call: { type: "tool-call" as const, id, name: "patch", input: { patchText } },
  129. })
  130. const exists = (target: string) =>
  131. Effect.promise(() =>
  132. fs.stat(target).then(
  133. () => true,
  134. () => false,
  135. ),
  136. )
  137. const it = testEffect(Layer.empty)
  138. describe("PatchTool", () => {
  139. it.live("registers and sequentially applies add, update, and delete hunks", () =>
  140. Effect.acquireUseRelease(
  141. Effect.promise(() => tmpdir()),
  142. (tmp) => {
  143. reset()
  144. const update = path.join(tmp.path, "update.txt")
  145. const remove = path.join(tmp.path, "remove.txt")
  146. return Effect.promise(() =>
  147. Promise.all([fs.writeFile(update, "before\n"), fs.writeFile(remove, "remove\n")]),
  148. ).pipe(
  149. Effect.andThen(
  150. withTool(tmp.path, (registry) =>
  151. Effect.gen(function* () {
  152. expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["patch"])
  153. const settled = yield* settleTool(
  154. registry,
  155. call(
  156. "*** Begin Patch\n*** Add File: nested/new.txt\n+created\n*** Update File: update.txt\n@@\n-before\n+after\n*** Delete File: remove.txt\n*** End Patch",
  157. ),
  158. )
  159. expect(settled.result).toEqual({
  160. type: "text",
  161. value: "Applied patch sequentially:\nA nested/new.txt\nM update.txt\nD remove.txt",
  162. })
  163. expect(settled.output?.structured).toMatchObject({
  164. applied: [
  165. { type: "add", resource: "nested/new.txt" },
  166. { type: "update", resource: "update.txt" },
  167. { type: "delete", resource: "remove.txt" },
  168. ],
  169. files: [
  170. {
  171. file: "nested/new.txt",
  172. status: "added",
  173. additions: 1,
  174. deletions: 0,
  175. patch: expect.stringContaining("+created"),
  176. },
  177. {
  178. file: "update.txt",
  179. status: "modified",
  180. additions: 1,
  181. deletions: 1,
  182. patch: expect.stringContaining("-before\n+after"),
  183. },
  184. {
  185. file: "remove.txt",
  186. status: "deleted",
  187. additions: 0,
  188. deletions: 1,
  189. patch: expect.stringContaining("-remove"),
  190. },
  191. ],
  192. })
  193. expect(assertions).toMatchObject([
  194. { sessionID, action: "edit", resources: ["nested/new.txt", "update.txt", "remove.txt"], save: ["*"] },
  195. ])
  196. expect(readsBeforeEditApproval).toBe(0)
  197. expect(yield* Effect.promise(() => fs.readFile(path.join(tmp.path, "nested/new.txt"), "utf8"))).toBe(
  198. "created\n",
  199. )
  200. expect(yield* Effect.promise(() => fs.readFile(update, "utf8"))).toBe("after\n")
  201. expect(yield* exists(remove)).toBe(false)
  202. }),
  203. ),
  204. ),
  205. )
  206. },
  207. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  208. ),
  209. )
  210. it.live("rejects moves before applying any hunk", () =>
  211. Effect.acquireUseRelease(
  212. Effect.promise(() => tmpdir()),
  213. (tmp) => {
  214. reset()
  215. const source = path.join(tmp.path, "old.txt")
  216. return Effect.promise(() => fs.writeFile(source, "before\n")).pipe(
  217. Effect.andThen(
  218. withTool(tmp.path, (registry) =>
  219. Effect.gen(function* () {
  220. expect(
  221. yield* executeTool(
  222. registry,
  223. call(
  224. "*** Begin Patch\n*** Add File: created.txt\n+created\n*** Update File: old.txt\n*** Move to: moved.txt\n@@\n-before\n+after\n*** End Patch",
  225. ),
  226. ),
  227. ).toEqual({ type: "error", value: "patch moves are not supported yet" })
  228. expect(yield* exists(path.join(tmp.path, "created.txt"))).toBe(false)
  229. expect(assertions).toEqual([])
  230. }),
  231. ),
  232. ),
  233. )
  234. },
  235. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  236. ),
  237. )
  238. it.live("approves an external directory and the batch before reading external update content", () =>
  239. Effect.acquireUseRelease(
  240. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  241. ([active, outside]) => {
  242. reset()
  243. const target = path.join(outside.path, "external.txt")
  244. return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
  245. Effect.andThen(
  246. withTool(active.path, (registry) =>
  247. Effect.gen(function* () {
  248. expect(
  249. yield* executeTool(
  250. registry,
  251. call(`*** Begin Patch\n*** Update File: ${target}\n@@\n-before\n+after\n*** End Patch`),
  252. ),
  253. ).toMatchObject({ type: "text" })
  254. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  255. expect(readsBeforeEditApproval).toBe(0)
  256. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\n")
  257. }),
  258. ),
  259. ),
  260. )
  261. },
  262. ([active, outside]) =>
  263. Effect.promise(() =>
  264. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  265. ),
  266. ),
  267. )
  268. it.live("approves one external directory scope for multiple files under the same parent", () =>
  269. Effect.acquireUseRelease(
  270. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  271. ([active, outside]) => {
  272. reset()
  273. const first = path.join(outside.path, "first.txt")
  274. const second = path.join(outside.path, "second.txt")
  275. return Effect.promise(() =>
  276. Promise.all([fs.writeFile(first, "before\n"), fs.writeFile(second, "before\n")]),
  277. ).pipe(
  278. Effect.andThen(
  279. withTool(active.path, (registry) =>
  280. Effect.gen(function* () {
  281. expect(
  282. yield* executeTool(
  283. registry,
  284. call(
  285. `*** Begin Patch\n*** Update File: ${first}\n@@\n-before\n+after\n*** Update File: ${second}\n@@\n-before\n+after\n*** End Patch`,
  286. ),
  287. ),
  288. ).toMatchObject({ type: "text" })
  289. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  290. expect(assertions[0]?.resources).toEqual([
  291. path.join(yield* Effect.promise(() => fs.realpath(outside.path)), "*").replaceAll("\\", "/"),
  292. ])
  293. }),
  294. ),
  295. ),
  296. )
  297. },
  298. ([active, outside]) =>
  299. Effect.promise(() =>
  300. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  301. ),
  302. ),
  303. )
  304. it.live("rejects invalid later update before applying an earlier add", () =>
  305. Effect.acquireUseRelease(
  306. Effect.promise(() => tmpdir()),
  307. (tmp) => {
  308. reset()
  309. return withTool(tmp.path, (registry) =>
  310. Effect.gen(function* () {
  311. expect(
  312. yield* executeTool(
  313. registry,
  314. call(
  315. "*** Begin Patch\n*** Add File: created.txt\n+created\n*** Update File: missing.txt\n@@\n-before\n+after\n*** End Patch",
  316. ),
  317. ),
  318. ).toEqual({ type: "error", value: "Unable to apply patch at missing.txt" })
  319. expect(yield* exists(path.join(tmp.path, "created.txt"))).toBe(false)
  320. }),
  321. )
  322. },
  323. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  324. ),
  325. )
  326. it.live("rejects add hunks targeting an existing file without replacing it", () =>
  327. Effect.acquireUseRelease(
  328. Effect.promise(() => tmpdir()),
  329. (tmp) => {
  330. reset()
  331. const target = path.join(tmp.path, "existing.txt")
  332. return Effect.promise(() => fs.writeFile(target, "sentinel\n")).pipe(
  333. Effect.andThen(
  334. withTool(tmp.path, (registry) =>
  335. Effect.gen(function* () {
  336. expect(
  337. yield* executeTool(
  338. registry,
  339. call("*** Begin Patch\n*** Add File: existing.txt\n+replacement\n*** End Patch"),
  340. ),
  341. ).toEqual({ type: "error", value: "Unable to apply patch at existing.txt" })
  342. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("sentinel\n")
  343. }),
  344. ),
  345. ),
  346. )
  347. },
  348. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  349. ),
  350. )
  351. it.live("rejects an add target that appears during permission approval", () =>
  352. Effect.acquireUseRelease(
  353. Effect.promise(() => tmpdir()),
  354. (tmp) => {
  355. reset()
  356. const target = path.join(tmp.path, "appeared.txt")
  357. afterEditApproval = () => Effect.promise(() => fs.writeFile(target, "winner\n")).pipe(Effect.orDie)
  358. return withTool(tmp.path, (registry) =>
  359. Effect.gen(function* () {
  360. expect(
  361. yield* executeTool(
  362. registry,
  363. call("*** Begin Patch\n*** Add File: appeared.txt\n+replacement\n*** End Patch"),
  364. ),
  365. ).toEqual({ type: "error", value: "Unable to apply patch at appeared.txt" })
  366. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("winner\n")
  367. }),
  368. )
  369. },
  370. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  371. ),
  372. )
  373. it.live("preserves a later commit defect after earlier sequential applications", () =>
  374. Effect.acquireUseRelease(
  375. Effect.promise(() => tmpdir()),
  376. (tmp) => {
  377. reset()
  378. const first = path.join(tmp.path, "first.txt")
  379. const second = path.join(tmp.path, "second.txt")
  380. failRemoveTarget = path.basename(second)
  381. return Effect.promise(() => Promise.all([fs.writeFile(first, "first"), fs.writeFile(second, "second")])).pipe(
  382. Effect.andThen(
  383. withTool(tmp.path, (registry) =>
  384. Effect.gen(function* () {
  385. expect(
  386. Exit.isFailure(
  387. yield* executeTool(
  388. registry,
  389. call("*** Begin Patch\n*** Delete File: first.txt\n*** Delete File: second.txt\n*** End Patch"),
  390. ).pipe(Effect.exit),
  391. ),
  392. ).toBe(true)
  393. expect(yield* exists(first)).toBe(false)
  394. expect(yield* exists(second)).toBe(true)
  395. }),
  396. ),
  397. ),
  398. )
  399. },
  400. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  401. ),
  402. )
  403. it.live("finishes the sequential commit phase when interrupted after the first mutation", () =>
  404. Effect.acquireUseRelease(
  405. Effect.promise(() => tmpdir()),
  406. (tmp) => {
  407. reset()
  408. const first = path.join(tmp.path, "first.txt")
  409. const second = path.join(tmp.path, "second.txt")
  410. blockRemoveTarget = path.basename(second)
  411. return Effect.gen(function* () {
  412. removeStarted = yield* Deferred.make<void>()
  413. releaseRemove = yield* Deferred.make<void>()
  414. yield* Effect.promise(() => Promise.all([fs.writeFile(first, "first"), fs.writeFile(second, "second")]))
  415. yield* withTool(tmp.path, (registry) =>
  416. Effect.gen(function* () {
  417. const run = yield* executeTool(
  418. registry,
  419. call("*** Begin Patch\n*** Delete File: first.txt\n*** Delete File: second.txt\n*** End Patch"),
  420. ).pipe(Effect.forkChild)
  421. yield* Deferred.await(removeStarted!)
  422. const interrupt = yield* Fiber.interrupt(run).pipe(Effect.forkChild)
  423. yield* Deferred.succeed(releaseRemove!, undefined)
  424. yield* Fiber.join(interrupt)
  425. expect(yield* exists(first)).toBe(false)
  426. expect(yield* exists(second)).toBe(false)
  427. }),
  428. )
  429. })
  430. },
  431. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  432. ),
  433. )
  434. })