tool-edit.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. import fs from "fs/promises"
  2. import path from "path"
  3. import { describe, expect } from "bun:test"
  4. import { Effect, Layer } from "effect"
  5. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  6. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  7. import { FileMutation } from "@opencode-ai/core/file-mutation"
  8. import { FSUtil } from "@opencode-ai/util/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 { EditTool } from "@opencode-ai/core/tool/edit"
  17. import { location } from "./fixture/location"
  18. import { tmpdir } from "./fixture/tmpdir"
  19. import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
  20. import { testEffect } from "./lib/effect"
  21. import { toolIdentity, executeTool, registerToolPlugin, settleTool, toolDefinitions } from "./lib/tool"
  22. const editToolNode = makeLocationNode({
  23. name: "test/edit-tool-plugin",
  24. layer: Layer.effectDiscard(registerToolPlugin(EditTool.Plugin)),
  25. deps: [ToolRegistry.toolsNode, LocationMutation.node, FileMutation.node, FSUtil.node, PermissionV2.node],
  26. })
  27. const sessionID = SessionV2.ID.make("ses_edit_tool_test")
  28. const assertions: PermissionV2.AssertInput[] = []
  29. const writes: string[] = []
  30. let reads = 0
  31. let denyAction: string | undefined
  32. let afterRead = (_target: string, _content: Uint8Array): Effect.Effect<void> => Effect.void
  33. const permission = Layer.succeed(
  34. PermissionV2.Service,
  35. PermissionV2.Service.of({
  36. assert: (input) =>
  37. Effect.sync(() => assertions.push(input)).pipe(
  38. Effect.andThen(
  39. input.action === denyAction
  40. ? Effect.fail(
  41. new PermissionV2.BlockedError({
  42. rules: [],
  43. permission: input.action,
  44. resources: input.resources,
  45. }),
  46. )
  47. : Effect.void,
  48. ),
  49. ),
  50. ask: () => Effect.die("unused"),
  51. reply: () => Effect.die("unused"),
  52. get: () => Effect.die("unused"),
  53. forSession: () => Effect.die("unused"),
  54. list: () => Effect.die("unused"),
  55. }),
  56. )
  57. const reset = () => {
  58. assertions.length = 0
  59. writes.length = 0
  60. reads = 0
  61. denyAction = undefined
  62. afterRead = () => Effect.void
  63. }
  64. const filesystem = Layer.effect(
  65. FSUtil.Service,
  66. Effect.gen(function* () {
  67. const fs = yield* FSUtil.Service
  68. return FSUtil.Service.of({
  69. ...fs,
  70. readFile: (target) =>
  71. fs
  72. .readFile(target)
  73. .pipe(
  74. Effect.tap((content) =>
  75. Effect.sync(() => reads++).pipe(Effect.andThen(Effect.suspend(() => afterRead(target, content)))),
  76. ),
  77. ),
  78. writeWithDirs: (target, content, mode) =>
  79. Effect.sync(() => writes.push(target)).pipe(Effect.andThen(fs.writeWithDirs(target, content, mode))),
  80. writeFile: (target, content, options) =>
  81. Effect.sync(() => writes.push(target)).pipe(Effect.andThen(fs.writeFile(target, content, options))),
  82. writeFileString: (target, content, options) =>
  83. Effect.sync(() => writes.push(target)).pipe(Effect.andThen(fs.writeFileString(target, content, options))),
  84. })
  85. }),
  86. ).pipe(Layer.provide(LayerNode.compile(FSUtil.node)))
  87. const withTool = <A, E, R>(directory: string, body: (registry: ToolRegistry.Interface) => Effect.Effect<A, E, R>) => {
  88. const activeLocation = Layer.succeed(
  89. Location.Service,
  90. Location.Service.of(location({ directory: AbsolutePath.make(directory) })),
  91. )
  92. return Effect.gen(function* () {
  93. return yield* body(yield* ToolRegistry.Service)
  94. }).pipe(
  95. Effect.provide(
  96. AppNodeBuilder.build(
  97. LayerNode.group([
  98. ToolRegistry.node,
  99. ToolRegistry.toolsNode,
  100. LocationMutation.node,
  101. FileMutation.node,
  102. editToolNode,
  103. ]),
  104. [
  105. [FSUtil.node, filesystem],
  106. [Location.node, activeLocation],
  107. [PermissionV2.node, permission],
  108. [ToolOutputStore.node, ToolOutputStore.nodeWithoutConfig],
  109. ],
  110. ),
  111. ),
  112. )
  113. }
  114. const call = (input: typeof EditTool.Input.Type, id = "call-edit") => ({
  115. sessionID,
  116. ...toolIdentity,
  117. call: { type: "tool-call" as const, id, name: "edit", input },
  118. })
  119. const it = testEffect(Layer.empty)
  120. describe("EditTool", () => {
  121. it.live("registers and replaces relative exact text through FileMutation once", () =>
  122. Effect.acquireUseRelease(
  123. Effect.promise(() => tmpdir()),
  124. (tmp) => {
  125. reset()
  126. const target = path.join(tmp.path, "hello.txt")
  127. return Effect.promise(() => fs.writeFile(target, "before\nrest\n")).pipe(
  128. Effect.andThen(
  129. withTool(tmp.path, (registry) =>
  130. Effect.gen(function* () {
  131. expect((yield* toolDefinitions(registry)).map((tool) => tool.name)).toEqual(["edit"])
  132. expect(yield* toolDefinitions(registry, [{ action: "edit", resource: "*", effect: "deny" }])).toEqual(
  133. [],
  134. )
  135. const settled = yield* settleTool(
  136. registry,
  137. call({ path: "hello.txt", oldString: "before", newString: "after" }),
  138. )
  139. expect(settled.result).toEqual({
  140. type: "text",
  141. value: "Edited file successfully: hello.txt\nReplacements: 1\n```diff\n-before\n+after\n```",
  142. })
  143. expect(settled.output?.structured).toEqual({
  144. replacements: 1,
  145. files: [
  146. {
  147. file: "hello.txt",
  148. status: "modified",
  149. additions: 1,
  150. deletions: 1,
  151. patch: expect.stringContaining("-before\n+after"),
  152. },
  153. ],
  154. })
  155. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\nrest\n")
  156. expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["hello.txt"], save: ["*"] }])
  157. expect(writes).toEqual([yield* Effect.promise(() => fs.realpath(target))])
  158. }),
  159. ),
  160. ),
  161. )
  162. },
  163. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  164. ),
  165. )
  166. it.live("accepts an absolute file path inside the active Location", () =>
  167. Effect.acquireUseRelease(
  168. Effect.promise(() => tmpdir()),
  169. (tmp) => {
  170. reset()
  171. const target = path.join(tmp.path, "absolute.txt")
  172. return Effect.promise(() => fs.writeFile(target, "before")).pipe(
  173. Effect.andThen(
  174. withTool(tmp.path, (registry) =>
  175. executeTool(registry, call({ path: target, oldString: "before", newString: "after" })),
  176. ),
  177. ),
  178. Effect.andThen((result) =>
  179. Effect.gen(function* () {
  180. expect(result.type).toBe("text")
  181. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  182. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after")
  183. }),
  184. ),
  185. )
  186. },
  187. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  188. ),
  189. )
  190. it.live("edits an external symlink target with only its in-location permission", () =>
  191. Effect.acquireUseRelease(
  192. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  193. ([active, outside]) => {
  194. reset()
  195. if (process.platform === "win32") return Effect.void
  196. const target = path.join(outside.path, "external.txt")
  197. const link = path.join(active.path, "link.txt")
  198. return Effect.promise(async () => {
  199. await fs.writeFile(target, "before")
  200. await fs.symlink(target, link)
  201. }).pipe(
  202. Effect.andThen(
  203. withTool(active.path, (registry) =>
  204. executeTool(registry, call({ path: "link.txt", oldString: "before", newString: "after" })),
  205. ),
  206. ),
  207. Effect.andThen((result) =>
  208. Effect.sync(() => {
  209. expect(result.type).toBe("text")
  210. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  211. expect(assertions[0]?.resources).toEqual(["link.txt"])
  212. }),
  213. ),
  214. Effect.andThen(Effect.promise(() => fs.readFile(target, "utf8"))),
  215. Effect.tap((content) => Effect.sync(() => expect(content).toBe("after"))),
  216. )
  217. },
  218. ([active, outside]) =>
  219. Effect.promise(() =>
  220. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  221. ),
  222. ),
  223. )
  224. it.live("approves an explicit external absolute path before edit", () =>
  225. Effect.acquireUseRelease(
  226. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  227. ([active, outside]) => {
  228. reset()
  229. const target = path.join(outside.path, "external.txt")
  230. return Effect.promise(() => fs.writeFile(target, "before")).pipe(
  231. Effect.andThen(
  232. withTool(active.path, (registry) =>
  233. executeTool(registry, call({ path: target, oldString: "before", newString: "after" })),
  234. ),
  235. ),
  236. Effect.andThen((result) =>
  237. Effect.gen(function* () {
  238. expect(result.type).toBe("text")
  239. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  240. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after")
  241. expect(writes).toHaveLength(1)
  242. }),
  243. ),
  244. )
  245. },
  246. ([active, outside]) =>
  247. Effect.promise(() =>
  248. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  249. ),
  250. ),
  251. )
  252. it.live("does not write when external_directory or edit approval is denied", () =>
  253. Effect.acquireUseRelease(
  254. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  255. ([active, outside]) =>
  256. Effect.gen(function* () {
  257. const external = path.join(outside.path, "denied.txt")
  258. yield* Effect.promise(() => fs.writeFile(external, "before"))
  259. reset()
  260. denyAction = "external_directory"
  261. expect(
  262. yield* withTool(active.path, (registry) =>
  263. executeTool(registry, call({ path: external, oldString: "before", newString: "after" })),
  264. ),
  265. ).toEqual({
  266. type: "error",
  267. value: `Unable to edit ${external}`,
  268. })
  269. expect(assertions.map((input) => input.action)).toEqual(["external_directory"])
  270. expect(reads).toBe(0)
  271. expect(writes).toEqual([])
  272. reset()
  273. denyAction = "edit"
  274. expect(
  275. yield* withTool(active.path, (registry) =>
  276. executeTool(registry, call({ path: external, oldString: "before", newString: "after" })),
  277. ),
  278. ).toEqual({
  279. type: "error",
  280. value: `Unable to edit ${external}`,
  281. })
  282. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  283. expect(reads).toBe(0)
  284. expect(writes).toEqual([])
  285. expect(yield* Effect.promise(() => fs.readFile(external, "utf8"))).toBe("before")
  286. }),
  287. ([active, outside]) =>
  288. Effect.promise(() =>
  289. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  290. ),
  291. ),
  292. )
  293. it.live("denied edit reads no target content and does not disclose whether oldString matches", () =>
  294. Effect.acquireUseRelease(
  295. Effect.promise(() => tmpdir()),
  296. (tmp) => {
  297. reset()
  298. denyAction = "edit"
  299. const target = path.join(tmp.path, "secret.txt")
  300. return Effect.promise(() => fs.writeFile(target, "secret content")).pipe(
  301. Effect.andThen(
  302. withTool(tmp.path, (registry) =>
  303. Effect.gen(function* () {
  304. const matching = yield* executeTool(
  305. registry,
  306. call({ path: "secret.txt", oldString: "secret content", newString: "replacement" }),
  307. )
  308. const missing = yield* executeTool(
  309. registry,
  310. call({ path: "secret.txt", oldString: "not present", newString: "replacement" }),
  311. )
  312. expect(matching).toEqual({ type: "error", value: "Unable to edit secret.txt" })
  313. expect(missing).toEqual(matching)
  314. expect(assertions.map((input) => input.action)).toEqual(["edit", "edit"])
  315. expect(reads).toBe(0)
  316. expect(writes).toEqual([])
  317. }),
  318. ),
  319. ),
  320. )
  321. },
  322. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  323. ),
  324. )
  325. it.live("rejects no-op, empty, missing, and ambiguous exact replacements", () =>
  326. Effect.acquireUseRelease(
  327. Effect.promise(() => tmpdir()),
  328. (tmp) => {
  329. reset()
  330. const target = path.join(tmp.path, "matches.txt")
  331. return Effect.promise(() => fs.writeFile(target, "same same")).pipe(
  332. Effect.andThen(
  333. withTool(tmp.path, (registry) =>
  334. Effect.gen(function* () {
  335. expect(
  336. yield* executeTool(registry, call({ path: "matches.txt", oldString: "same", newString: "same" })),
  337. ).toEqual({
  338. type: "error",
  339. value: "No changes to apply: oldString and newString are identical.",
  340. })
  341. expect(
  342. yield* executeTool(registry, call({ path: "matches.txt", oldString: "", newString: "after" })),
  343. ).toEqual({
  344. type: "error",
  345. value: "oldString must not be empty. Use write to create or overwrite a file.",
  346. })
  347. expect(
  348. yield* executeTool(registry, call({ path: "matches.txt", oldString: "missing", newString: "after" })),
  349. ).toEqual({
  350. type: "error",
  351. value:
  352. "Could not find oldString in the file. It must match exactly, including whitespace and indentation.",
  353. })
  354. expect(
  355. yield* executeTool(registry, call({ path: "matches.txt", oldString: "same", newString: "after" })),
  356. ).toEqual({
  357. type: "error",
  358. value:
  359. "Found multiple exact matches for oldString. Provide more surrounding context or set replaceAll to true.",
  360. })
  361. expect(writes).toEqual([])
  362. }),
  363. ),
  364. ),
  365. )
  366. },
  367. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  368. ),
  369. )
  370. it.live("replaces every exact occurrence when replaceAll is true", () =>
  371. Effect.acquireUseRelease(
  372. Effect.promise(() => tmpdir()),
  373. (tmp) => {
  374. reset()
  375. const target = path.join(tmp.path, "all.txt")
  376. return Effect.promise(() => fs.writeFile(target, "same same same")).pipe(
  377. Effect.andThen(
  378. withTool(tmp.path, (registry) =>
  379. settleTool(registry, call({ path: "all.txt", oldString: "same", newString: "after", replaceAll: true })),
  380. ),
  381. ),
  382. Effect.andThen((settled) =>
  383. Effect.gen(function* () {
  384. expect(settled.output?.structured).toMatchObject({ replacements: 3 })
  385. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after after after")
  386. expect(writes).toHaveLength(1)
  387. }),
  388. ),
  389. )
  390. },
  391. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  392. ),
  393. )
  394. it.live("preserves BOM and CRLF line endings", () =>
  395. Effect.acquireUseRelease(
  396. Effect.promise(() => tmpdir()),
  397. (tmp) => {
  398. reset()
  399. const target = path.join(tmp.path, "windows.txt")
  400. return Effect.promise(() => fs.writeFile(target, "\uFEFFbefore\r\nrest\r\n")).pipe(
  401. Effect.andThen(
  402. withTool(tmp.path, (registry) =>
  403. executeTool(registry, call({ path: "windows.txt", oldString: "before\nrest", newString: "after\nrest" })),
  404. ),
  405. ),
  406. Effect.andThen(() => Effect.promise(() => fs.readFile(target, "utf8"))),
  407. Effect.tap((content) => Effect.sync(() => expect(content).toBe("\uFEFFafter\r\nrest\r\n"))),
  408. )
  409. },
  410. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  411. ),
  412. )
  413. it.live("rejects an in-place content change after matching but before conditional commit", () =>
  414. Effect.acquireUseRelease(
  415. Effect.promise(() => tmpdir()),
  416. (tmp) => {
  417. reset()
  418. const target = path.join(tmp.path, "concurrent.txt")
  419. afterRead = () => (reads === 1 ? Effect.promise(() => fs.writeFile(target, "newer\n")) : Effect.void)
  420. return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
  421. Effect.andThen(
  422. withTool(tmp.path, (registry) =>
  423. executeTool(registry, call({ path: "concurrent.txt", oldString: "before", newString: "after" })),
  424. ),
  425. ),
  426. Effect.andThen((result) =>
  427. Effect.gen(function* () {
  428. expect(result).toEqual({
  429. type: "error",
  430. value: "File changed after permission approval. Read it again before editing.",
  431. })
  432. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("newer\n")
  433. expect(writes).toEqual([])
  434. }),
  435. ),
  436. )
  437. },
  438. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  439. ),
  440. )
  441. })