tool-apply-patch.test.ts 16 KB

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