tool-apply-patch.test.ts 17 KB

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