tool-edit.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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, 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", "execute"])
  132. expect(
  133. (yield* toolDefinitions(registry, [{ action: "edit", resource: "*", effect: "deny" }])).map(
  134. (tool) => tool.name,
  135. ),
  136. ).toEqual(["execute"])
  137. const settled = yield* executeTool(
  138. registry,
  139. call({ path: "hello.txt", oldString: "before", newString: "after" }),
  140. )
  141. expect(settled.status).toBe("completed")
  142. if (settled.status !== "completed") return
  143. expect(settled.content).toEqual([
  144. {
  145. type: "text",
  146. text: "Edited file successfully: hello.txt\nReplacements: 1\n```diff\n-before\n+after\n```",
  147. },
  148. ])
  149. // Compact UI metadata carries the file diffs the TUI renders.
  150. expect(settled.metadata).toMatchObject({
  151. files: [{ file: "hello.txt", status: "modified", additions: 1, deletions: 1 }],
  152. })
  153. expect(settled.output).toEqual({
  154. replacements: 1,
  155. files: [
  156. {
  157. file: "hello.txt",
  158. status: "modified",
  159. additions: 1,
  160. deletions: 1,
  161. patch: expect.stringContaining("-before\n+after"),
  162. },
  163. ],
  164. })
  165. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after\nrest\n")
  166. expect(assertions).toMatchObject([{ sessionID, action: "edit", resources: ["hello.txt"], save: ["*"] }])
  167. expect(writes).toEqual([yield* Effect.promise(() => fs.realpath(target))])
  168. }),
  169. ),
  170. ),
  171. )
  172. },
  173. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  174. ),
  175. )
  176. it.live("accepts an absolute file path inside the active Location", () =>
  177. Effect.acquireUseRelease(
  178. Effect.promise(() => tmpdir()),
  179. (tmp) => {
  180. reset()
  181. const target = path.join(tmp.path, "absolute.txt")
  182. return Effect.promise(() => fs.writeFile(target, "before")).pipe(
  183. Effect.andThen(
  184. withTool(tmp.path, (registry) =>
  185. executeTool(registry, call({ path: target, oldString: "before", newString: "after" })),
  186. ),
  187. ),
  188. Effect.andThen((result) =>
  189. Effect.gen(function* () {
  190. expect(result.status).toBe("completed")
  191. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  192. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after")
  193. }),
  194. ),
  195. )
  196. },
  197. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  198. ),
  199. )
  200. it.live("edits an external symlink target with only its in-location permission", () =>
  201. Effect.acquireUseRelease(
  202. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  203. ([active, outside]) => {
  204. reset()
  205. if (process.platform === "win32") return Effect.void
  206. const target = path.join(outside.path, "external.txt")
  207. const link = path.join(active.path, "link.txt")
  208. return Effect.promise(async () => {
  209. await fs.writeFile(target, "before")
  210. await fs.symlink(target, link)
  211. }).pipe(
  212. Effect.andThen(
  213. withTool(active.path, (registry) =>
  214. executeTool(registry, call({ path: "link.txt", oldString: "before", newString: "after" })),
  215. ),
  216. ),
  217. Effect.andThen((result) =>
  218. Effect.sync(() => {
  219. expect(result.status).toBe("completed")
  220. expect(assertions.map((input) => input.action)).toEqual(["edit"])
  221. expect(assertions[0]?.resources).toEqual(["link.txt"])
  222. }),
  223. ),
  224. Effect.andThen(Effect.promise(() => fs.readFile(target, "utf8"))),
  225. Effect.tap((content) => Effect.sync(() => expect(content).toBe("after"))),
  226. )
  227. },
  228. ([active, outside]) =>
  229. Effect.promise(() =>
  230. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  231. ),
  232. ),
  233. )
  234. it.live("approves an explicit external absolute path before edit", () =>
  235. Effect.acquireUseRelease(
  236. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  237. ([active, outside]) => {
  238. reset()
  239. const target = path.join(outside.path, "external.txt")
  240. return Effect.promise(() => fs.writeFile(target, "before")).pipe(
  241. Effect.andThen(
  242. withTool(active.path, (registry) =>
  243. executeTool(registry, call({ path: target, oldString: "before", newString: "after" })),
  244. ),
  245. ),
  246. Effect.andThen((result) =>
  247. Effect.gen(function* () {
  248. expect(result.status).toBe("completed")
  249. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  250. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after")
  251. expect(writes).toHaveLength(1)
  252. }),
  253. ),
  254. )
  255. },
  256. ([active, outside]) =>
  257. Effect.promise(() =>
  258. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  259. ),
  260. ),
  261. )
  262. it.live("does not write when external_directory or edit approval is denied", () =>
  263. Effect.acquireUseRelease(
  264. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  265. ([active, outside]) =>
  266. Effect.gen(function* () {
  267. const external = path.join(outside.path, "denied.txt")
  268. yield* Effect.promise(() => fs.writeFile(external, "before"))
  269. reset()
  270. denyAction = "external_directory"
  271. expect(
  272. yield* withTool(active.path, (registry) =>
  273. executeTool(registry, call({ path: external, oldString: "before", newString: "after" })),
  274. ),
  275. ).toEqual({
  276. status: "error",
  277. error: { type: "permission.rejected", message: "Permission denied: external_directory" },
  278. })
  279. expect(assertions.map((input) => input.action)).toEqual(["external_directory"])
  280. expect(reads).toBe(0)
  281. expect(writes).toEqual([])
  282. reset()
  283. denyAction = "edit"
  284. expect(
  285. yield* withTool(active.path, (registry) =>
  286. executeTool(registry, call({ path: external, oldString: "before", newString: "after" })),
  287. ),
  288. ).toEqual({
  289. status: "error",
  290. error: { type: "permission.rejected", message: "Permission denied: edit" },
  291. })
  292. expect(assertions.map((input) => input.action)).toEqual(["external_directory", "edit"])
  293. expect(reads).toBe(0)
  294. expect(writes).toEqual([])
  295. expect(yield* Effect.promise(() => fs.readFile(external, "utf8"))).toBe("before")
  296. }),
  297. ([active, outside]) =>
  298. Effect.promise(() =>
  299. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  300. ),
  301. ),
  302. )
  303. it.live("denied edit reads no target content and does not disclose whether oldString matches", () =>
  304. Effect.acquireUseRelease(
  305. Effect.promise(() => tmpdir()),
  306. (tmp) => {
  307. reset()
  308. denyAction = "edit"
  309. const target = path.join(tmp.path, "secret.txt")
  310. return Effect.promise(() => fs.writeFile(target, "secret content")).pipe(
  311. Effect.andThen(
  312. withTool(tmp.path, (registry) =>
  313. Effect.gen(function* () {
  314. const matching = yield* executeTool(
  315. registry,
  316. call({ path: "secret.txt", oldString: "secret content", newString: "replacement" }),
  317. )
  318. const missing = yield* executeTool(
  319. registry,
  320. call({ path: "secret.txt", oldString: "not present", newString: "replacement" }),
  321. )
  322. expect(matching).toEqual({
  323. status: "error",
  324. error: { type: "permission.rejected", message: "Permission denied: edit" },
  325. })
  326. expect(missing).toEqual(matching)
  327. expect(assertions.map((input) => input.action)).toEqual(["edit", "edit"])
  328. expect(reads).toBe(0)
  329. expect(writes).toEqual([])
  330. }),
  331. ),
  332. ),
  333. )
  334. },
  335. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  336. ),
  337. )
  338. it.live("rejects no-op, empty, missing, and ambiguous exact replacements", () =>
  339. Effect.acquireUseRelease(
  340. Effect.promise(() => tmpdir()),
  341. (tmp) => {
  342. reset()
  343. const target = path.join(tmp.path, "matches.txt")
  344. return Effect.promise(() => fs.writeFile(target, "same same")).pipe(
  345. Effect.andThen(
  346. withTool(tmp.path, (registry) =>
  347. Effect.gen(function* () {
  348. expect(
  349. yield* executeTool(registry, call({ path: "matches.txt", oldString: "same", newString: "same" })),
  350. ).toEqual({
  351. status: "error",
  352. error: {
  353. type: "tool.execution",
  354. message: "No changes to apply: oldString and newString are identical.",
  355. },
  356. })
  357. expect(
  358. yield* executeTool(registry, call({ path: "matches.txt", oldString: "", newString: "after" })),
  359. ).toEqual({
  360. status: "error",
  361. error: {
  362. type: "tool.execution",
  363. message: "oldString must not be empty. Use write to create or overwrite a file.",
  364. },
  365. })
  366. expect(
  367. yield* executeTool(registry, call({ path: "matches.txt", oldString: "missing", newString: "after" })),
  368. ).toEqual({
  369. status: "error",
  370. error: {
  371. type: "tool.execution",
  372. message:
  373. "Could not find oldString in the file. It must match exactly, including whitespace and indentation.",
  374. },
  375. })
  376. expect(
  377. yield* executeTool(registry, call({ path: "matches.txt", oldString: "same", newString: "after" })),
  378. ).toEqual({
  379. status: "error",
  380. error: {
  381. type: "tool.execution",
  382. message:
  383. "Found multiple exact matches for oldString. Provide more surrounding context or set replaceAll to true.",
  384. },
  385. })
  386. expect(writes).toEqual([])
  387. }),
  388. ),
  389. ),
  390. )
  391. },
  392. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  393. ),
  394. )
  395. it.live("replaces every exact occurrence when replaceAll is true", () =>
  396. Effect.acquireUseRelease(
  397. Effect.promise(() => tmpdir()),
  398. (tmp) => {
  399. reset()
  400. const target = path.join(tmp.path, "all.txt")
  401. return Effect.promise(() => fs.writeFile(target, "same same same")).pipe(
  402. Effect.andThen(
  403. withTool(tmp.path, (registry) =>
  404. executeTool(registry, call({ path: "all.txt", oldString: "same", newString: "after", replaceAll: true })),
  405. ),
  406. ),
  407. Effect.andThen((settled) =>
  408. Effect.gen(function* () {
  409. expect(settled.status).toBe("completed")
  410. if (settled.status !== "completed") return
  411. expect(settled.output).toMatchObject({ replacements: 3 })
  412. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("after after after")
  413. expect(writes).toHaveLength(1)
  414. }),
  415. ),
  416. )
  417. },
  418. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  419. ),
  420. )
  421. it.live("preserves BOM and CRLF line endings", () =>
  422. Effect.acquireUseRelease(
  423. Effect.promise(() => tmpdir()),
  424. (tmp) => {
  425. reset()
  426. const target = path.join(tmp.path, "windows.txt")
  427. return Effect.promise(() => fs.writeFile(target, "\uFEFFbefore\r\nrest\r\n")).pipe(
  428. Effect.andThen(
  429. withTool(tmp.path, (registry) =>
  430. executeTool(registry, call({ path: "windows.txt", oldString: "before\nrest", newString: "after\nrest" })),
  431. ),
  432. ),
  433. Effect.andThen(() => Effect.promise(() => fs.readFile(target, "utf8"))),
  434. Effect.tap((content) => Effect.sync(() => expect(content).toBe("\uFEFFafter\r\nrest\r\n"))),
  435. )
  436. },
  437. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  438. ),
  439. )
  440. it.live("rejects an in-place content change after matching but before conditional commit", () =>
  441. Effect.acquireUseRelease(
  442. Effect.promise(() => tmpdir()),
  443. (tmp) => {
  444. reset()
  445. const target = path.join(tmp.path, "concurrent.txt")
  446. afterRead = () => (reads === 1 ? Effect.promise(() => fs.writeFile(target, "newer\n")) : Effect.void)
  447. return Effect.promise(() => fs.writeFile(target, "before\n")).pipe(
  448. Effect.andThen(
  449. withTool(tmp.path, (registry) =>
  450. executeTool(registry, call({ path: "concurrent.txt", oldString: "before", newString: "after" })),
  451. ),
  452. ),
  453. Effect.andThen((result) =>
  454. Effect.gen(function* () {
  455. // The message-less StaleContentError cause must not erase the tool's
  456. // curated failure message; the canonical error is the sole authority.
  457. expect(result).toEqual({
  458. status: "error",
  459. error: {
  460. type: "tool.execution",
  461. message: "File changed after permission approval. Read it again before editing.",
  462. },
  463. })
  464. expect(yield* Effect.promise(() => fs.readFile(target, "utf8"))).toBe("newer\n")
  465. expect(writes).toEqual([])
  466. }),
  467. ),
  468. )
  469. },
  470. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  471. ),
  472. )
  473. })